Is there an Underscore.js function that can map one object to another object, based on the other object's properties?
(Kind of how AutoMapper works in .NET.)
For example:
var objectA = { 'name': 'Jonathan', 'city': 'Sydney' };
var objectB = { 'name': 'Jonathan Conway', 'city': 'Sydney', 'errors': [] }
_.mapperMethod(objectB);
=> { 'name': 'Jonathan Conway', 'city': 'Sydney' };
Possibly _.extend()
:
_.extend(objectA, objectB);
console.log(objectA);
// { 'name': 'Jonathan Conway', 'city': 'Sydney', 'errors': [] }
If you don't want to pick up 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' }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With