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.
// 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" })
); |
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’).
// 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)); |
Output:
{
amit: [ { susanta: 20, chinmoy: 30 }, { durgam: 40, kripamoy: 50 } ]
}