Skip to content
Related Articles

Related Articles

Improve Article

Lodash _.merge() Method

  • Last Updated : 13 Sep, 2020

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




// 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:  

Javascript




// Requiring the lodash library  
const _ = require("lodash");  
  
// The destination object
var object = {
  'amit': [{ 'susanta': 20 }, { 'durgam': 40 }]
};
  
// The source object
var other = {
  'amit': [{ 'chinmoy': 30 }, { 'kripamoy': 50 }]
};
  
// Using the _.merge() method
console.log(_.merge(object, other));

Output:

{ 'amit': [{'chinmoy': 30, 'susanta': 20 }, 
{ 'durgam': 40, 'kripamoy': 50 }] }



My Personal Notes arrow_drop_up
Recommended Articles
Page :