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; }
Run code snippetEdit code snippet Hide Results Copy to answer Expand

Answer from Samathingamajig on Stack Overflow
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › lodash-_-merge-method
Lodash _.merge() Method - GeeksforGeeks
Lodash _.merge() method is used to merge two or more objects, starting from the left-most to the right-most to create a parent mapping object.
Published: August 5, 2025
🌐
CoreUI
coreui.io › blog › how-to-merge-objects-in-javascript
How to Merge Objects in JavaScript · CoreUI
February 27, 2024 - This method goes beyond the surface, recursively merging objects at all levels, making it ideal for complex data structures. Lodash’s merge() ensures that every layer of nested properties is combined, offering a level of depth that native JavaScript methods don’t directly provide.
Discussions

Is there a benefit to using lodash.merge (or other utilities of the same feature) versus merging via object destructuring?
Yes, absolutely. Lodash merge recursively merges properties at every level. If you merged two objects with destructuring (or lodash.assign or Object.assign which are equivalent), it drops anything that is not top-level from the first object. See: https://lodash.com/docs#merge More on reddit.com
🌐 r/node
13
4
November 14, 2022
How to merge two arrays of objects by ID using lodash?
_.mixin({ 'mergeByKey' : function(arr1, ... '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; } More on stackoverflow.com
🌐 stackoverflow.com
Lodash - How to merge two arrays of objects based on key?
I want to avoid the repetition of an object with the same id...Which kind of operator can I use? ... Save this answer. ... Show activity on this post. You can get the result using merge and keyBy lodash functions. More on stackoverflow.com
🌐 stackoverflow.com
How to use Lodash to merge two collections based on a key?
Lodash has a merge method that works on objects (objects with the same key are merged). In this demo, the arrays a and b are first converted into objects (where userId is the key), then merged, and the result converted back to an array (_.values) (getting rid of the keys). More on stackoverflow.com
🌐 stackoverflow.com
🌐
GitHub
gist.github.com › ahtcx › 0cd94e62691f539160b32ecda18af3d6
Deep-Merge JavaScript objects with ES6 · GitHub
I think the most "mind expanding: pointer I could give would be to check out what the lodash library has to offer for deep merging.The basic deep merge (https://lodash.com/docs/#merge) merges the arrays index by index, rather than append and dedupe, as shown in the example.
🌐
Dustin John Pfister
dustinpfister.github.io › 2017 › 11 › 17 › lodash_merge
_.merge in lodash as a means to recursively merge down objects. | Dustin John Pfister at github pages
November 25, 2021 - However it most cases I often want to merge them down like that of a bunch of sheets of acetate rather than that of paper. That is if a certain value is in one object, but not any other, it is the value that will end up in the final object. That is the effect that is achieved when using the lodash _.merge method.
🌐
TutorialsPoint
tutorialspoint.com › lodash › lodash_merge.htm
Lodash - merge method
Lodash - Object · Lodash - Seq ... is like _.assign except that it recursively merges own and inherited enumerable string keyed properties of source objects into the destination object....
🌐
Flavio Copes
flaviocopes.com › home › javascript › how to merge two objects in javascript
How to merge two objects in JavaScript - Flavio Copes
September 18, 2026 - import merge from 'lodash.merge' const merged = merge({}, person, update) // { name: 'Flavio', address: { city: 'Rome', zip: '20100' } } Here city was updated and zip was preserved, because the nested objects were merged property by property.
🌐
Mastering JS
masteringjs.io › tutorials › lodash › merge
Lodash's `merge()` Function - Mastering JS
Given two objects destination and source, Lodash's merge() function copies the 2nd object's own properties and inherited properties into the first object.
Find elsewhere
🌐
Marius Schulz
mariusschulz.com › blog › combining-settings-objects-with-lodash-assign-or-merge
Combining Settings Objects with Lodash: _.assign or _.merge? — Marius Schulz
July 28, 2026 - The _.merge function has the same signature as _.assign, but behaves a little differently. Instead of assigning values as a whole, it recursively merges properties that don't hold the value undefined into the target object.
🌐
Lodash
lodash.com › docs
Lodash Documentation
The iteratee is invoked with four arguments: (accumulator, value, index|key, collection). Many lodash methods are guarded to work as iteratees for methods like _.reduce, _.reduceRight, and _.transform. The guarded methods are: assign, defaults, defaultsDeep, includes, merge, orderBy, and sortBy
🌐
Tim Mousk
timmousk.com › blog › lodash-merge
How Does The Lodash Merge Function Work? – Tim Mouskhelichvili
March 6, 2023 - The Lodash merge function merges two or more objects into one.
🌐
egghead.io
egghead.io › lessons › javascript-deep-merge-objects-in-javascript-with-spread-lodash-and-deepmerge
Deep Merge Objects in JavaScript with Spread, Lodash, and Deepmerge | egghead.io
Back in the file, we can require lodash and then use lodash's merge function, which will handle the deep merge for us. We can say that the merged value is the merge of person and update.
Published: January 17, 2019
Top answer
1 of 2
65

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>

2 of 2
58

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);

🌐
StudyRaid
app.studyraid.com › en › read › 11765 › 373056 › merging-objects-with-merge
Understand merging objects with _.merge
The _.merge method in Lodash is a powerful utility for merging two or more objects into a single object. Unlike shallow merging methods, _.merge performs a deep merge, meaning it recursively combines properties from source objects into the ...
🌐
GeeksforGeeks
geeksforgeeks.org › how-to-merge-array-of-objects-by-property-using-lodash
How to Merge Array of Objects by Property using Lodash? | GeeksforGeeks
August 22, 2024 - Replacing objects in an array using Lodash typically involves identifying the specific object(s) you want to replace and then performing the replacement operation. Lodash provides a range of methods to facilitate such operations, although the actual replacement might involve combining Lodash functio
🌐
Medium
medium.com › @ryan_forrester_ › javascript-combine-two-objects-quick-guide-bd37bf89d0d6
Javascript Combine Two Objects (Quick Guide) | by ryan | Medium
September 10, 2024 - Deep Merging: If you need to merge nested objects, consider using a method that supports deep merging, such as Lodash’s _.merge(). The spread operator and Object.assign() only perform shallow copies.
Top answer
1 of 6
65

Second highest voted answer doesn't do proper merge. If second array contains an unique property, it is not taken into account.

This approach does a proper merge.

Lodash

var a = [
  { userId:"p1", item:1},
  { userId:"p2", item:2},
  { userId:"p3", item:4}
];

var b = [
  { userId:"p1", profile:1},
  { userId:"p2", profile:2},
  { userId:"p4", profile:4}
];
var merged = _.merge(_.keyBy(a, 'userId'), _.keyBy(b, 'userId'));
var values = _.values(merged);
console.log(values);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>
Run code snippetEdit code snippet Hide Results Copy to answer Expand

ES6+

// from https://stackoverflow.com/a/34749873/80766
const mergeDeep = (target, ...sources) => {
  if (!sources.length) return target;
  const source = sources.shift();

  if (target instanceof Object && source instanceof Object) {
    for (const key in source) {
      if (source[key] instanceof Object) {
        if (!target[key]) Object.assign(target, { [key]: {} });
        mergeDeep(target[key], source[key]);
      } else {
        Object.assign(target, { [key]: source[key] });
      }
    }
  }

  return mergeDeep(target, ...sources);
}

const a = [
  { userId:"p1", item:1},
  { userId:"p2", item:2},
  { userId:"p3", item:4}
];

const b = [
  { userId:"p1", profile:1},
  { userId:"p2", profile:2},
  { userId:"p4", profile:4}
];


const aKeyed = a.reduce((acc, cur) => ({ ...acc, [cur.userId]: cur }), {});
const bKeyed = b.reduce((acc, cur) => ({ ...acc, [cur.userId]: cur }), {});
const merged = mergeDeep(aKeyed, bKeyed);
const values = Object.values(merged);
console.log(values);
Run code snippetEdit code snippet Hide Results Copy to answer Expand

2 of 6
44

You can use _.map(), _.assign() and _.find().

// Iterate over first array of objects
_.map(a, function(obj) {

    // add the properties from second array matching the userID
    // to the object from first array and return the updated object
    return _.assign(obj, _.find(b, {userId: obj.userId}));
});

Fiddle Demo

Show code snippet

var a = [{
    userId: "p1",
    item: 1
}, {
    userId: "p2",
    item: 2
}, {
    userId: "p3",
    item: 4
}];

var b = [{
    userId: "p1",
    profile: 1
}, {
    userId: "p2",
    profile: 2
}];

var arrResult = _.map(a, function(obj) {
    return _.assign(obj, _.find(b, {
        userId: obj.userId
    }));
});

console.log(arrResult);
document.getElementById('result').innerHTML = JSON.stringify(arrResult, 0, 4);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.1.0/lodash.min.js"></script>
<pre id="result"></pre>
Run code snippetEdit code snippet Hide Results Copy to answer Expand