Open In App

Underscore.js _.merge() Method

Last Updated : 14 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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.

Javascript




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

Javascript




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

Javascript




// 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' }


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads