Lodash is a JavaScript library that works on the top of underscore.js. Lodash helps in working with arrays, strings, objects, numbers, etc.
The _.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 value for the rightmost key. If more than one object is the same, the newly generated object will have only one key and value corresponding to those objects.
Syntax:
_.merge( object, sources )
Parameters: This method accepts two parameters as mentioned above and described below:
- object: This parameter holds the destination object.
- sources: This parameter holds the source object. It is an optional parameter.
Return Value: This method returns the merged object.
Example 1:
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:
Javascript
const _ = require( "lodash" );
var object = {
'amit' : [{ 'susanta' : 20 }, { 'durgam' : 40 }]
};
var other = {
'amit' : [{ 'chinmoy' : 30 }, { 'kripamoy' : 50 }]
};
console.log(_.merge(object, other));
|
Output:
{ 'amit': [{'chinmoy': 30, 'susanta': 20 },
{ 'durgam': 40, 'kripamoy': 50 }] }