Lodash _.merge() method is used to merge two or more objects starting with 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: The _.merge() method mutates the object.
Syntax:
_.merge(object, [sources])
Parameters:
- object parameter holds the destination object.
- sources parameter holds the source object. It is an optional parameter.
Return Value:
This method returns the merged object.
Example 1: In this example, 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
const _ = require( "lodash" );
console.log(
_.merge({ cpp: "12" }, { java: "23" },
{ python: "35" })
);
console.log(
_.merge({ cpp: "12" }, { cpp: "23" },
{ java: "23" }, { python: "35" })
);
console.log(
_.merge({ cpp: "12" }, { cpp: "12" },
{ java: "23" }, { python: "35" })
);
|
Output:
{ cpp: '12', java: '23', python: '35' }
{ cpp: '23', java: '23', python: '35' }
{ cpp: '12', java: '23', python: '35' }
Example 2: In this 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
const _ = require( "lodash" );
let object = {
'amit' : [{ 'susanta' : 20 }, { 'durgam' : 40 }]
};
let other = {
'amit' : [{ 'chinmoy' : 30 }, { 'kripamoy' : 50 }]
};
console.log(_.merge(object, other));
|
Output:
{
amit: [ { susanta: 20, chinmoy: 30 }, { durgam: 40, kripamoy: 50 } ]
}
Last Updated :
18 Oct, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...