Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Underscore.js object-object mapper?

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' };
like image 912
Jonathan Avatar asked Aug 09 '13 06:08

Jonathan


1 Answers

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' }
like image 200
Jonathan Lonowski Avatar answered Oct 09 '22 14:10

Jonathan Lonowski