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

javascript - Lodash merge two objects but replace the same key values with new object value - Stack Overflow
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) More on stackoverflow.com
🌐 stackoverflow.com
javascript - Lodash - How to merge two arrays of objects based on key? - Stack Overflow
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
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
javascript - How to merge two arrays of objects by ID using lodash? - Stack Overflow
Communities for your favorite technologies. Explore all Collectives · Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work More on stackoverflow.com
🌐 stackoverflow.com
🌐
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 - This bites hard with configuration objects, where you merge user options over defaults and a whole section of the defaults silently disappears. The best solution in this case is to use Lodash and its merge() method, which will perform a deeper ...
🌐
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
We'll use spread here to say that we want to concatenate the two arrays together. [03:56] Now when we run that, it works. We get a deeply merged object with the pet array handled like we want. When merging objects, the spread operator works great. It's fully customizable, but it can get tedious if the objects are very deeply nested or of an unknown structure. [04:12] Lodash's merge works, but only if we want to treat arrays like objects.
Published: January 17, 2019
🌐
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.
🌐
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 - 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. In this section I will be starting out with some simple examples of the lodash merge method. Although I will be keeping these examples very simple I assume that you have at least some experience with javaScript, and can also get to the point where you are including lodash in the javaScript environment that you are developing in.
🌐
Tim Mousk
timmousk.com › blog › lodash-merge
How Does The Lodash Merge Function Work? – Tim Mouskhelichvili
March 6, 2023 - If two or more keys are the same, the generated object will take the value from the rightmost argument. When it comes to the bundle size, Lodash is a very big package. That's why, I recommend not using the default import, but rather importing the functions that you need individually. There are two ways of importing Lodash functions individually. ... The one-by-one import will result in the smallest bundle size. Here is a small example for you of how to use this function. javascriptimport { merge } from 'lodash'; const obj1 = { a: 'a', b: 'b' }; const obj2 = { c: 'c', d: 'd' }; const obj3 = { a: 'z', f: 'f' }; // Outputs: '{ a: "a", b: "b", c: "c", d: "d" } console.log(merge(obj1, obj2)); // Outputs: '{ a: "z", c: "c", d: "d", f: "f" }' console.log(merge(obj2, obj3)); // Outputs: '{ a: "z", b: "b", c: "c", d: "d", f: "f" }' console.log(merge(obj1, obj2, obj3));
Find elsewhere
🌐
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.
🌐
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 - Now, the formatting object hasn't been replaced by the partial user definition, but has had its default values merged with the user settings. So, if you intend to perform a deep merge of user-provided settings with your own default values, use _.merge rather than _.assign. ES2015 brought a native Promise implementation to the JavaScript standard library.
🌐
TutorialsPoint
tutorialspoint.com › lodash › lodash_merge.htm
Lodash - merge method
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. object (Object) − The destination object. [sources] (...Object) − The source objects. (Object) − Returns object. var _ = require('lodash'); var object = { 'a': [{ 'b': 2 }, { 'd': 4 }] }; var other = { 'a': [{ 'c': 3 }, { 'e': 5 }] }; console.log(_.merge(object, other)); Save the above program in tester.js.
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);

🌐
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 - Using the splice() method on a nested array of objects in JavaScript allows you to modify the structure of the nested array by adding or removing elements at specified positions. Table of Content Accessing the nested array directlyUtilizing ...
🌐
Thesyntaxdiaries
thesyntaxdiaries.com › lodash-merge-a-comprehensive-guide
Lodash _.merge() Deep Merge Objects & Arrays — Guide
February 9, 2026 - Lodash _.merge() is a JavaScript utility method that recursively deep merges properties of source objects into a destination object.
🌐
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.
🌐
egghead.io
egghead.io › lessons › javascript-build-lodash-merge-from-scratch
Build lodash.merge from Scratch | egghead.io
May 26, 2020 - After getting basic types to merge we'll show off two methods for merging arrays, either using concat or recursively going through the children and merging them. Finally we'll build our own isObject function to check for object literals and recursively apply our mergeJSON function to any object literals in our source object. And last we'll add support for multiple source objects to be merged in using a for...of loop. ... The mergeJSON method we create approximates the lodash.merge functionality but does not seek to replace it.
Top answer
1 of 7
122

_.unionBy():
This method is like _.union except that it accepts iteratee which is invoked for each element of each arrays to generate the criterion by which uniqueness is computed. Result values are chosen from the first array in which the value occurs.

var original = [
  { label: 'private', value: 'private@johndoe.com' },
  { label: 'work', value: 'work@johndoe.com' }
];

var update = [
  { label: 'private', value: 'me@johndoe.com' },
  { label: 'school', value: 'schol@johndoe.com' }
];

var result = _.unionBy(update, original, "label");

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>
Run code snippetEdit code snippet Hide Results Copy to answer Expand

2 of 7
5

Convert the lists to objects keyed by label, merge them by _.assign, and convert it back to an array. It will even retain order of the items on most browsers.

var original = [
  {
    label: 'private',
    value: 'private@johndoe.com'
  },
  {
    label: 'work',
    value: 'work@johndoe.com'
  }
];

var update = [
  {
    label: 'private',
    value: 'me@johndoe.com'
  },
  {
    label: 'school',
    value: 'schol@johndoe.com'
  }
];

console.log(
  _.map(
    _.assign(
      _.mapKeys(original, v => v.label),
      _.mapKeys(update, v => v.label)
    )
  )
);


// or remove more duplicated code using spread

console.log(
  _.map(
    _.assign(
      ...[original, update].map(
        coll => _.mapKeys(coll, v => v.label)
      )
    )
  )
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.js"></script>
Run code snippetEdit code snippet Hide Results Copy to answer Expand

🌐
Scaler
scaler.com › home › topics › javascript merge objects
JavaScript Merge Objects - Scaler Topics
May 4, 2023 - Explanation Here in this example, we are using lodash library's _.merge() function to merge two objects, what it does is, it recursively merges properties of the source object into the target object. Here even if the keys are identical, then instead of overwriting the complete object, it simply ...