Sunday, April 5, 2026
HomeLanguagesJavascriptUnderscore.js _.merge() Method

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




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


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




// 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);


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




// 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);


Output: 

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

Example 4: 

Javascript




// 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);


Output: 

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

Most Popular

Dominic
32512 POSTS0 COMMENTS
Milvus
131 POSTS0 COMMENTS
Nango Kala
6886 POSTS0 COMMENTS
Nicole Veronica
12007 POSTS0 COMMENTS
Nokonwaba Nkukhwana
12100 POSTS0 COMMENTS
Shaida Kate Naidoo
7015 POSTS0 COMMENTS
Ted Musemwa
7259 POSTS0 COMMENTS
Thapelo Manthata
6972 POSTS0 COMMENTS
Umr Jansen
6960 POSTS0 COMMENTS