Last Updated : 05 Aug, 2025
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. When two keys are the same, the generated object will have a value for the rightmost key.
If more than one object is the same, the newly generated object will have only one key (most right side) and value corresponding to those objects.
Note: It modifies the original (target) object directly.
Syntax
_.merge(object, [sources])
Parameters:
Return Value: This method returns the merged object.
Let's now understand _.merge() Method with an exampleHere, when two keys are the same, then only the right-most key will be added to a new array, and if more than two objects are the same, then it will add only one.
JavaScript
// Requiring the lodash library
const _ = require("lodash");
// Using the _.merge() method
console.log(
_.merge({ cpp: "12" }, { java: "23" },
{ python: "35" })
);
// When two keys are the same
console.log(
_.merge({ cpp: "12" }, { cpp: "23" },
{ java: "23" }, { python: "35" })
);
// When more than one object is the same
console.log(
_.merge({ cpp: "12" }, { cpp: "12" },
{ java: "23" }, { python: "35" })
);
In this example
cpp
) exists in multiple objects, the value from the last object encountered is used in the merged result.cpp
), and again, the final value is determined by the last object containing that key.Output
{ cpp: '12', java: '23', python: '35' } { cpp: '23', java: '23', python: '35' } { cpp: '12', java: '23', python: '35' }How Does Lodash _.merge() Work?
Now let's understand _.merge() method with one more example
When we are merging two different objects then it will merge recursively (one right-most element from 'other' and one right-most element from 'object').
JavaScript
// Requiring the lodash library
const _ = require("lodash");
// The destination object
let object = {
'amit': [{ 'susanta': 20 }, { 'durgam': 40 }]
};
// The source object
let other = {
'amit': [{ 'chinmoy': 30 }, { 'kripamoy': 50 }]
};
// Using the _.merge() method
console.log(_.merge(object, other));
In this example:
Output:
{ amit: [ { susanta: 20, chinmoy: 30 }, { durgam: 40, kripamoy: 50 } ] }Use Case of Lodash _.merge() Method
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.
A common use case for _.merge() is combining configuration settings from different sources. For example, when you have:
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4