This method is like Object.assign
except that it recursively merges own enumerable string keyed properties of source objects into the destination object. Source properties that resolve to undefined
are skipped if a destination value exists. Arrays are concatenated. 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.
Note: This method mutates target
.
- The native
Object.assign
does simply overwrite values on duplicate keys. - The Lodash
_.merge
does not handle arrays the way I would expect it:
// Lodash returns [{}]
_.merge([{}], [{}])
// This returns [{}, {}]
merge([{}], [{}])
The order of objects within arrays does not necessarily matter. Lodash merges objects that have the same index within different arrays. This might lead to unexpected results if the objects are unrelated.
My real world use case was merging multiple OpenAPI specifications of several microservices into one big REST documentation for an API gateway.
const object = {
a: [{b: 2}, {d: 4}]
};
const other = {
a: [{c: 3}, {e: 5}]
};
// 1. Native JavaScript
Object.assign(object, other);
// = {a: [{c: 3}, {e: 5}]}
// 2. Lodash
_.merge(object, other);
// = {a: [{b: 2, c: 3}, {d: 4, e: 5}]}
// 3. This merge
merge(object, other);
// = {a: [{b: 2}, {d: 4}, {c: 3}, {e: 5}]}