You can turn both arrays into objects using _.keyBy(arr, 'label'), and then merge deep using _.merge():

var originalAddresses = [{
  label: 'home',
  address: {
    city: 'London',
    zipCode: '12345'
  }
}, {
  label: 'work',
  address: {
    city: 'New York',
    zipCode: '54321'
  }
}];

var updatedAddresses = [{
  label: 'home',
  address: {
    city: 'London (Central)',
    country: 'UK'
  }
}, {
  label: 'spain',
  address: {
    city: 'Madrid',
    zipCode: '55555'
  }
}];

var result = _.values(_.merge(
  _.keyBy(originalAddresses, 'label'),
  _.keyBy(updatedAddresses, 'label')
));

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>

Answer from Ori Drori on Stack Overflow
Top answer
1 of 3
59

You can turn both arrays into objects using _.keyBy(arr, 'label'), and then merge deep using _.merge():

var originalAddresses = [{
  label: 'home',
  address: {
    city: 'London',
    zipCode: '12345'
  }
}, {
  label: 'work',
  address: {
    city: 'New York',
    zipCode: '54321'
  }
}];

var updatedAddresses = [{
  label: 'home',
  address: {
    city: 'London (Central)',
    country: 'UK'
  }
}, {
  label: 'spain',
  address: {
    city: 'Madrid',
    zipCode: '55555'
  }
}];

var result = _.values(_.merge(
  _.keyBy(originalAddresses, 'label'),
  _.keyBy(updatedAddresses, 'label')
));

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>

2 of 3
1

I try to use VanillaJS to handle this.

const originalAddresses = [{
    label: 'home',
    address: {
        city: 'London',
        zipCode: '12345'
    }
}, {
    label: 'work',
    address: {
        city: 'New York',
        zipCode: '54321'
    }
}];

const updatedAddresses = [{
    label: 'home',
    address: {
        city: 'London (Central)',
        country: 'UK'
    }
}, {
    label: 'spain',
    address: {
        city: 'Madrid',
        zipCode: '55555'
    }
}];


const groupBy = (array, property) => {
    return array.reduce((acc, cur) => {
            let key = cur[property]
            if (!acc[key]) {
                acc[key] = []
            }
            acc[key].push(cur)

            return acc
        }
        , {})
}

const groupByLabel = groupBy([...originalAddresses, ...updatedAddresses], 'label')

const result  = Object.keys(groupByLabel).map((key) => {
        return {
            label: groupByLabel[key][0].label,
            address: groupByLabel[key].reduce((acc, cur) => {
                    return Object.assign(acc, cur.address)
                }
                , {})
        }
    }
)
console.log(result)

🌐
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
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 can I perform a deep merge rather than a shallow merge?
Standard JavaScript methods like Object.assign and the object spread operator create shallow merges. Consider this issue: // Flat structure const obj1 = { key1: 5 }; const obj2 = { key2: 7 }; const mergedObj = { ...obj1, ...obj2 }; // { key1: 5, key2: 7 } This behaves as expected. More on community.latenode.com
🌐 community.latenode.com
0
0
October 12, 2024
_.merge perform deep cloning of constructor function instances
In 4.13 version, where i'll update from 3.10, suddenly all constructor instances, stored in object properties, began deeply cloning when call _.merge. For example var instance = new SomeConstru... More on github.com
🌐 github.com
6
June 8, 2016
Lodash Merge
Use the fp versions https://github.com/lodash/lodash/wiki/FP-Guide More on reddit.com
🌐 r/node
52
38
February 1, 2022
🌐
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. Be careful here.
Published   January 17, 2019
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › lodash-_-merge-method
Lodash _.merge() Method - GeeksforGeeks
The Lodash _.merge() method is primarily used when you need to combine multiple objects, especially when dealing with nested structures, ensuring that both top-level properties and deep properties (within objects or arrays) are merged properly.
Published   August 5, 2025
🌐
Latenode
community.latenode.com › other questions › javascript
How can I perform a deep merge rather than a shallow merge?
October 12, 2024 - Standard JavaScript methods like Object.assign and the object spread operator create shallow merges. Consider this issue: // Flat structure const obj1 = { key1: 5 }; const obj2 = { key2: 7 }; const mergedObj = { ...obj1, ...obj2 }; // { key1: 5, key2: 7 } This behaves as expected.
🌐
npm
npmjs.com › package › lodash-deepmerge
lodash-deepmerge - npm
Manage deeply merging objects as well as the arrays they contain.. Latest version: 1.0.0, last published: 4 years ago. Start using lodash-deepmerge in your project by running `npm i lodash-deepmerge`. There are 1 other projects in the npm registry using lodash-deepmerge.
      » npm install lodash-deepmerge
    
Published   Aug 22, 2021
Version   1.0.0
Author   Max Shapira
🌐
The Syntax Diaries
thesyntaxdiaries.com › lodash-merge-a-comprehensive-guide
Lodash _.merge() Deep Merge Objects & Arrays — Guide with Examples
November 12, 2024 - Lodash _.merge() is a JavaScript utility method that recursively deep merges properties of source objects into a destination object.
Find elsewhere
🌐
npm
npmjs.com › package › lodash.merge
lodash.merge - npm
July 10, 2019 - The Lodash method `_.merge` exported as a module.. Latest version: 4.6.2, last published: 7 years ago. Start using lodash.merge in your project by running `npm i lodash.merge`. There are 7028 other projects in the npm registry using lodash.merge.
      » npm install lodash.merge
    
Published   Jul 10, 2019
Version   4.6.2
Author   John-David Dalton
🌐
GitHub
github.com › lodash › lodash › issues › 5320
Deep merge with exception · Issue #5320 · lodash/lodash
We want to deeply merge dest object into source using _.merge(source, dest) method. But we want to except object property 'b' inside two objects from being deeply merged.
Author   ghost
🌐
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, ...
🌐
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 - When you have a whole bunch of nested objects in an object do you want to just copy the first level into a new object, or do you want to recursively copy everything? In sort a shallow clone of an object is nit the same thing as a deep clone of one. The lodash _.merge differs from lodash _.assign method in that _.assign will create a new object for my deltas overwriting any values that may exist in any lower object.
🌐
Mastering JS
masteringjs.io › tutorials › lodash › merge
Lodash's `merge()` Function - Mastering JS
The first detail is that merge() copies objects recursively, so _.merge() is a deep copy whereas _.assign() is a shallow copy.
🌐
CoreUI
coreui.io › blog › how-to-merge-objects-in-javascript
How to Merge Objects in JavaScript · CoreUI
February 27, 2024 - When your project requires deep merging, the Lodash library offers a powerful solution with its merge() function. This method goes beyond the surface, recursively merging objects at all levels, making it ideal for complex data structures.
🌐
GitHub
github.com › lodash › lodash › issues › 2410
_.merge perform deep cloning of constructor function instances · Issue #2410 · lodash/lodash
June 8, 2016 - In 4.13 version, where i'll update from 3.10, suddenly all constructor instances, stored in object properties, began deeply cloning when call _.merge. For example var instance = new SomeConstructor(); var sourceObj = { name: 'some_object...
Author   SkReD
🌐
Tim Mousk
timmousk.com › blog › lodash-merge
How Does The Lodash Merge Function Work? – Tim Mouskhelichvili
March 6, 2023 - merge function if you want the final generated object created from deep copies. Use it to deep merge two or more objects. If you do not need the deep copy feature you can use: ... Object.assign function.
🌐
NPM Compare
npm-compare.com › deepmerge,immer,lodash.merge
deepmerge vs lodash.merge vs immer: Which is Better JavaScript Object Merging Libraries?
Lodash.merge performs a recursive merge of properties, allowing you to combine objects while handling arrays and other data types. If you are already using Lodash in your project, lodash.merge can be a convenient option for merging objects. To see how deepmerge compares with immer and lodash.merge, ...
🌐
Medium
medium.com › @abbas.ashraf19 › 8-best-methods-for-merging-nested-objects-in-javascript-ff3c813016d9
8 Best Methods for Merging Nested Objects in JavaScript | by Abbas Ashraf Mughal | Medium
February 15, 2024 - const jsonString1 = JSON.strin... deepMergedObjJSON = JSON.parse(mergedJsonString); Lodash is a popular utility library with a merge function that handles deep merging efficiently....
🌐
Marius Schulz
mariusschulz.com › blog › combining-settings-objects-with-lodash-assign-or-merge
Combining Settings Objects with Lodash: _.assign or _.merge? — Marius Schulz
November 1, 2020 - Much better! 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.