Underscore.js _.merge() Method

The _.merge() method merges two or more objects starting with the left-most to the rightmost to create a parent mapping object.

Syntax:

_.merge(obj1, obj2,..., objn);

Parameters: This method takes n objects to merge them.

Return Value: This method returns a newly generated merged object.

Note: This will not work in normal JavaScript because it requires the underscore.js contrib library to be installed. 



underscore.js contrib library can be installed using npm install underscore-contrib –save.

Example 1: 

Javascript

filter_none

edit
close

play_arrow

link
brightness_4
code

// Defining underscore contrib variable
var _ = require('underscore-contrib'); 
  
var obj = _.merge({ a: "1" }, { b: "2" }, { c:"3" });;
  
console.log("Generated Mapping Object: ", obj);

chevron_right


Output:

Generated Mapping Object:  { a: '1', b: '2', c: '3' }

Example 2: if two keys are the same, the generated object will have value for the rightmost key.

Javascript

filter_none

edit
close

play_arrow

link
brightness_4
code

// Defining underscore contrib variable
var _ = require('underscore-contrib'); 
  
var obj = _.merge({ a: "1" }, { a: "2" }, 
                  { b: "2" }, { c:"3" });;
  
console.log("Generated Mapping Object: ", obj);

chevron_right


Output: 

Generated Mapping Object:  { a: '2', b: '2', c: '3' }

Example 3: If more than one object is the same, the newly generated object will have only one key and value corresponding to those objects.

Javascript

filter_none

edit
close

play_arrow

link
brightness_4
code

// Defining underscore contrib variable
var _ = require('underscore-contrib'); 
  
var obj = _.merge({ a: "1" }, { a: "1" }, 
                  { b: "2" }, { c:"3" });;
  
console.log("Generated Mapping Object: ", obj);

chevron_right


Output: 

Generated Mapping Object:  { a: '1', b: '2', c: '3' }

Example 4: 

Javascript

filter_none

edit
close

play_arrow

link
brightness_4
code

// Defining underscore contrib variable
var _ = require('underscore-contrib'); 
  
var obj = _.merge({ a: "1",  d: "4"}, 
                  { a: "1" }, { b: "2" }, 
                  { c:"3" });;
  
console.log("Generated Mapping Object: ", obj);

chevron_right


Output: 

Generated Mapping Object:  { a: '1', d: '4', b: '2', c: '3' }

full-stack-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.