Object-Object Mapping in javascript

Viewed 6761

Based on an array of keys, is there any way to map one object with another object?

var obj1 = { 'firstName': 'Tom', 'lastName': 'Hardy', 'age': 32 };
var obj2 = { 'firstName': 'Jon', 'lastName': 'Snow', 'age': 33 };
keys = ['lastName', 'age'];

I want to update the value of lastName and age of obj1's by the obj2's value.

Is there any lodash function available for this type of mapping?

2 Answers

With pure Javascript you can do it using Array#forEach function to iterate over the keys and use [] notation to access the properties based on other variable's value.

var obj1 = { 'firstName': 'Tom', 'lastName': 'Hardy', 'age': 32 };
var obj2 = { 'firstName': 'Jon', 'lastName': 'Snow', 'age': 33 };
var keys = ['lastName', 'age'];

keys.forEach(prop => obj1[prop] = obj2[prop]);

console.log(obj1);

With lodash#forEach

var obj1 = { 'firstName': 'Tom', 'lastName': 'Hardy', 'age': 32 };
var obj2 = { 'firstName': 'Jon', 'lastName': 'Snow', 'age': 33 };
var keys = ['lastName', 'age'];

_.forEach(keys, prop => obj1[prop] = obj2[prop]);

console.log(obj1);
<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js'></script>

You can use lodash#assign and lodash#pick to achieve this result.

_.assign(obj1, _.pick(obj2, keys));

var obj1 = { 'firstName': 'Tom', 'lastName': 'Hardy', 'age': 32 };
var obj2 = { 'firstName': 'Jon', 'lastName': 'Snow', 'age': 33 };
var keys = ['lastName', 'age'];

_.assign(obj1, _.pick(obj2, keys));

console.log(obj1);
.as-console-wrapper{min-height:100%;top:0;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

Alternatively, here's an immutable solution using lodash#pick and lodash#defaults:

var result = _(obj2).pick(keys).defaults(obj1);

var obj1 = { 'firstName': 'Tom', 'lastName': 'Hardy', 'age': 32 };
var obj2 = { 'firstName': 'Jon', 'lastName': 'Snow', 'age': 33 };
var keys = ['lastName', 'age'];

var result = _(obj2).pick(keys).defaults(obj1);

console.log(result);
.as-console-wrapper{min-height:100%;top:0;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

Related