Underscore.js _.merge() 方法
_.merge() 方法从最左边到最右边合并两个或多个对象,以创建父映射对象。
句法:
_.merge(obj1, obj2,..., objn);
参数:此方法需要n 个对象来合并它们。
返回值:该方法返回一个新生成的合并对象。
注意:这在普通 JavaScript 中不起作用,因为它需要安装 underscore.js contrib 库。
underscore.js contrib 库可以使用npm install underscore-contrib –save 安装。
示例 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);
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);
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);
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);
输出:
Generated Mapping Object: { a: '1', b: '2', c: '3' }
示例 2:如果两个键相同,则生成的对象将具有最右边键的值。
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);
输出:
Generated Mapping Object: { a: '2', b: '2', c: '3' }
示例3:如果多个对象相同,则新生成的对象将只有一个键和值与这些对象对应。
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);
输出:
Generated Mapping Object: { a: '1', b: '2', c: '3' }
示例 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);
输出:
Generated Mapping Object: { a: '1', d: '4', b: '2', c: '3' }