Underscore.js object-object mapper?

Is there a function Underscore.js that can map one object to another object based on other properties of the object?

(View of how AutoMapper works in .NET.)

For instance:

var objectA = { 'name': 'Jonathan', 'city': 'Sydney' }; var objectB = { 'name': 'Jonathan Conway', 'city': 'Sydney', 'errors': [] } _.mapperMethod(objectB); => { 'name': 'Jonathan Conway', 'city': 'Sydney' }; 
+6
source share
3 answers

Maybe _.extend() :

 _.extend(objectA, objectB); console.log(objectA); // { 'name': 'Jonathan Conway', 'city': 'Sydney', 'errors': [] } 

If you do not want to take additional keys, you can use it with _.keys() and _.pick() :

 var keys = _.keys(objectA); _.extend(objectA, _.pick(objectB, keys)); console.log(objectA); // { 'name': 'Jonathan Conway', 'city': 'Sydney' } 
+10
source
 Below is my auto mapper var sourceObj, desObj; var map: function (source, destination) { var desKeys = _.keys(destination), functions; _.extend(destination, _.pick(source, desKeys)); sourceObj = source; desObj = destination; functions = { forMember: function (sourceKey, desKey) { var keys = sourceKey.split('.'), sourceValue = sourceObj, index = 0; // incase sourceKey is a nested object like objectA.Value if (keys.length) { while (index < keys.length) { sourceValue = sourceValue[keys[index]]; index++; } desObj[desKey] = sourceValue; } else { desObj[desKey] = sourceObj[sourceKey]; } return functions; } }; return functions; } var mapList: function (listSource, listDestination) { _.each(listDestination, function(destination, i){ var source = listSource[i]; map(source,destination); }); functions = { forMember: function (sourceKey, desKey) { _.each(listDestination, function(destination, i){ var source = listSource[i]; map(source,destination) .forMember(sourceKey, desKey); }); return functions; } }; return functions; } and how to use it var source = { Name: 'Nguyen Tran', Age: '30', Address: { Street: '121 Le Van Viet', City: 'HCM' } }; var destination = { Name: 'test', age: '25', Street: '', City: '' }; autoMapper.map(source, destination) .forMember('Age', 'age') .forMember('Address.Street', 'Street') .forMember('Address.City', 'City') Hope this work for you. 
+2
source

Over the past couple of months, I have managed to create a fairly complete port of the AutoMapper library for TypeScript / JavaScript: AutoMapperTS. The port - among many other features - supports alignment / nesting and asynchronous mappings.

For more information about the AutoMapperTS library, including how to install it using NPM and Bower, check out the library on GitHub: http://b.ldmn.nl/AutoMapperTS

0
source

Source: https://habr.com/ru/post/951369/


All Articles