Open In App

Underscore.js _.merge() Method

Underscore.js _.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: This example shows the use of the Underscore.js _.merge() method.




// Defining underscore contrib variable
let _ = require('underscore-contrib');
 
let 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 a value for the rightmost key.




// Defining underscore contrib variable
let _ = require('underscore-contrib');
 
let 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.




// Defining underscore contrib variable
let _ = require('underscore-contrib');
 
let 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' }

Article Tags :