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