Lodash is trying to be helpful by recursively merging subobjects
This method is like _.assign except that it recursively merges own and inherited enumerable string keyed properties of source objects into the destination object. Source properties that resolve to undefined are skipped if a destination value exists. Array and plain object properties are merged recursively. Other objects and value types are overridden by assignment. Source objects are applied from left to right. Subsequent sources overwrite property assignments of previous sources.
https://lodash.com/docs/4.17.15#merge (emphasis mine)
If you don't want this to happen, just use the standard ES6 spread operator ... or Object.assign
const object1 = {
name: 'John',
age: 23,
books: ['book1', 'book2']
};
const object2 = {
name: 'John',
age: 23,
books: ['book3'],
city: 'London'
};
object3 = {...object1, ...object2};
object4 = Object.assign({}, object1, object2);
console.log(object3);
console.log(object4);
/* make the Stack Overflow console bigger */ .as-console-wrapper { max-height: 100vh !important; }
Answer from Samathingamajig on Stack OverflowLodash merge including undefined values
Lodash merge two objects but replace the same key values with new object value
Lodash - difference between .extend() / .assign() and .merge()
Is there a benefit to using lodash.merge (or other utilities of the same feature) versus merging via object destructuring?
Here's how extend/assign works: For each property in source, copy its value as-is to destination. if property values themselves are objects, there is no recursive traversal of their properties. Entire object would be taken from source and set in to destination.
Here's how merge works: For each property in source, check if that property is object itself. If it is then go down recursively and try to map child object properties from source to destination. So essentially we merge object hierarchy from source to destination. While for extend/assign, it's simple one level copy of properties from source to destination.
Here's simple JSBin that would make this crystal clear: http://jsbin.com/uXaqIMa/2/edit?js,console
Here's more elaborate version that includes array in the example as well: http://jsbin.com/uXaqIMa/1/edit?js,console
Lodash version 3.10.1
Methods compared
_.merge(object, [sources], [customizer], [thisArg])_.assign(object, [sources], [customizer], [thisArg])_.extend(object, [sources], [customizer], [thisArg])_.defaults(object, [sources])_.defaultsDeep(object, [sources])
Similarities
- None of them work on arrays as you might expect
_.extendis an alias for_.assign, so they are identical- All of them seem to modify the target object (first argument)
- All of them handle
nullthe same
Differences
_.defaultsand_.defaultsDeepprocesses the arguments in reverse order compared to the others (though the first argument is still the target object)_.mergeand_.defaultsDeepwill merge child objects and the others will overwrite at the root level- Only
_.assignand_.extendwill overwrite a value withundefined
Tests
They all handle members at the root in similar ways.
_.assign ({}, { a: 'a' }, { a: 'bb' }) // => { a: "bb" }
_.merge ({}, { a: 'a' }, { a: 'bb' }) // => { a: "bb" }
_.defaults ({}, { a: 'a' }, { a: 'bb' }) // => { a: "a" }
_.defaultsDeep({}, { a: 'a' }, { a: 'bb' }) // => { a: "a" }
_.assign handles undefined but the others will skip it
_.assign ({}, { a: 'a' }, { a: undefined }) // => { a: undefined }
_.merge ({}, { a: 'a' }, { a: undefined }) // => { a: "a" }
_.defaults ({}, { a: undefined }, { a: 'bb' }) // => { a: "bb" }
_.defaultsDeep({}, { a: undefined }, { a: 'bb' }) // => { a: "bb" }
They all handle null the same
_.assign ({}, { a: 'a' }, { a: null }) // => { a: null }
_.merge ({}, { a: 'a' }, { a: null }) // => { a: null }
_.defaults ({}, { a: null }, { a: 'bb' }) // => { a: null }
_.defaultsDeep({}, { a: null }, { a: 'bb' }) // => { a: null }
But only _.merge and _.defaultsDeep will merge child objects
_.assign ({}, {a:{a:'a'}}, {a:{b:'bb'}}) // => { "a": { "b": "bb" }}
_.merge ({}, {a:{a:'a'}}, {a:{b:'bb'}}) // => { "a": { "a": "a", "b": "bb" }}
_.defaults ({}, {a:{a:'a'}}, {a:{b:'bb'}}) // => { "a": { "a": "a" }}
_.defaultsDeep({}, {a:{a:'a'}}, {a:{b:'bb'}}) // => { "a": { "a": "a", "b": "bb" }}
And none of them will merge arrays it seems
_.assign ({}, {a:['a']}, {a:['bb']}) // => { "a": [ "bb" ] }
_.merge ({}, {a:['a']}, {a:['bb']}) // => { "a": [ "bb" ] }
_.defaults ({}, {a:['a']}, {a:['bb']}) // => { "a": [ "a" ] }
_.defaultsDeep({}, {a:['a']}, {a:['bb']}) // => { "a": [ "a" ] }
All modify the target object
a={a:'a'}; _.assign (a, {b:'bb'}); // a => { a: "a", b: "bb" }
a={a:'a'}; _.merge (a, {b:'bb'}); // a => { a: "a", b: "bb" }
a={a:'a'}; _.defaults (a, {b:'bb'}); // a => { a: "a", b: "bb" }
a={a:'a'}; _.defaultsDeep(a, {b:'bb'}); // a => { a: "a", b: "bb" }
None really work as expected on arrays
Note: As @Mistic pointed out, Lodash treats arrays as objects where the keys are the index into the array.
_.assign ([], ['a'], ['bb']) // => [ "bb" ]
_.merge ([], ['a'], ['bb']) // => [ "bb" ]
_.defaults ([], ['a'], ['bb']) // => [ "a" ]
_.defaultsDeep([], ['a'], ['bb']) // => [ "a" ]
_.assign ([], ['a','b'], ['bb']) // => [ "bb", "b" ]
_.merge ([], ['a','b'], ['bb']) // => [ "bb", "b" ]
_.defaults ([], ['a','b'], ['bb']) // => [ "a", "b" ]
_.defaultsDeep([], ['a','b'], ['bb']) // => [ "a", "b" ]
Is there some kind of edge case that lodash (or other merge utilities) takes care of that const output = {...a, ...b} doesn't? (Assuming a and b are both valid)
If both arrays are in the correct order; where each item corresponds to its associated member identifier then you can simply use.
var merge = _.merge(arr1, arr2);
Which is the short version of:
var merge = _.chain(arr1).zip(arr2).map(function(item) {
return _.merge.apply(null, item);
}).value();
Or, if the data in the arrays is not in any particular order, you can look up the associated item by the member value.
var merge = _.map(arr1, function(item) {
return _.merge(item, _.find(arr2, { 'member' : item.member }));
});
You can easily convert this to a mixin. See the example below:
_.mixin({
'mergeByKey' : function(arr1, arr2, key) {
var criteria = {};
criteria[key] = null;
return _.map(arr1, function(item) {
criteria[key] = item[key];
return _.merge(item, _.find(arr2, criteria));
});
}
});
var arr1 = [{
"member": 'ObjectId("57989cbe54cf5d2ce83ff9d6")',
"bank": 'ObjectId("575b052ca6f66a5732749ecc")',
"country": 'ObjectId("575b0523a6f66a5732749ecb")'
}, {
"member": 'ObjectId("57989cbe54cf5d2ce83ff9d8")',
"bank": 'ObjectId("575b052ca6f66a5732749ecc")',
"country": 'ObjectId("575b0523a6f66a5732749ecb")'
}];
var arr2 = [{
"member": 'ObjectId("57989cbe54cf5d2ce83ff9d8")',
"name": 'yyyyyyyyyy',
"age": 26
}, {
"member": 'ObjectId("57989cbe54cf5d2ce83ff9d6")',
"name": 'xxxxxx',
"age": 25
}];
var arr3 = _.mergeByKey(arr1, arr2, 'member');
document.body.innerHTML = JSON.stringify(arr3, null, 4);
body { font-family: monospace; white-space: pre; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.14.0/lodash.min.js"></script>
Create dictionaries for both arrays using _.keyBy(), merge the dictionaries, and convert the result to an array with _.values(). In this way, the order of the arrays doesn't matter. In addition, it can also handle arrays of different length.
const ObjectId = (id) => id; // mock of ObjectId
const arr1 = [{"member" : ObjectId("57989cbe54cf5d2ce83ff9d8"),"bank" : ObjectId("575b052ca6f66a5732749ecc"),"country" : ObjectId("575b0523a6f66a5732749ecb")},{"member" : ObjectId("57989cbe54cf5d2ce83ff9d6"),"bank" : ObjectId("575b052ca6f66a5732749ecc"),"country" : ObjectId("575b0523a6f66a5732749ecb")}];
const arr2 = [{"member" : ObjectId("57989cbe54cf5d2ce83ff9d6"),"name" : 'xxxxxx',"age" : 25},{"member" : ObjectId("57989cbe54cf5d2ce83ff9d8"),"name" : 'yyyyyyyyyy',"age" : 26}];
const merged = _(arr1) // start sequence
.keyBy('member') // create a dictionary of the 1st array
.merge(_.keyBy(arr2, 'member')) // create a dictionary of the 2nd array, and merge it to the 1st
.values() // turn the combined dictionary to array
.value(); // get the value (array) out of the sequence
console.log(merged);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.14.0/lodash.min.js"></script>
Using ES6 Map
Concat the arrays, and reduce the combined array to a Map. Use Object#assign to combine objects with the same member to a new object, and store in map. Convert the map to an array with Map#values and spread:
const ObjectId = (id) => id; // mock of ObjectId
const arr1 = [{"member" : ObjectId("57989cbe54cf5d2ce83ff9d8"),"bank" : ObjectId("575b052ca6f66a5732749ecc"),"country" : ObjectId("575b0523a6f66a5732749ecb")},{"member" : ObjectId("57989cbe54cf5d2ce83ff9d6"),"bank" : ObjectId("575b052ca6f66a5732749ecc"),"country" : ObjectId("575b0523a6f66a5732749ecb")}];
const arr2 = [{"member" : ObjectId("57989cbe54cf5d2ce83ff9d6"),"name" : 'xxxxxx',"age" : 25},{"member" : ObjectId("57989cbe54cf5d2ce83ff9d8"),"name" : 'yyyyyyyyyy',"age" : 26}];
const merged = [...arr1.concat(arr2).reduce((m, o) =>
m.set(o.member, Object.assign(m.get(o.member) || {}, o))
, new Map()).values()];
console.log(merged);
You can get the result using merge and keyBy lodash functions.
var array1 = [{id:1, name:'doc1'}, {id:2, name:'doc2'}];
var array2 = [{id:1, name:'doc1'}, {id:3, name:'doc3'}, {id:4, name:'doc4'}];
var merged = _.merge(_.keyBy(array1, 'id'), _.keyBy(array2, 'id'));
var values = _.values(merged);
console.log(values);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>
Use _.unionBy() to combine two arrays, and remove duplicates that have the same unique field (id in this case). The lodash's union methods create an array of unique values. The _.unionBy() method accepts an iteratee which is invoked for each element of each array to generate the criterion by which uniqueness is computed.
const array1 = [{id:1, name:'doc1'}, {id:2, name:'doc2'}];
const array2 = [{id:1, name:'doc1'}, {id:3, name:'doc3'}, {id:4, name:'doc4'}];
const result = _.unionBy(array1, array2, 'id');
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>
ยป npm install lodash.merge