我需要能够在运行时合并两个(非常简单)JavaScript对象。例如,我想:
var obj1 = { food: 'pizza', car: 'ford' }
var obj2 = { animal: 'dog' }
obj1.merge(obj2);
//obj1 now has three properties: food, car, and animal
是否有一种内置的方法来实现这一点?我不需要递归,也不需要合并函数,只需要平面对象上的方法。
我需要能够在运行时合并两个(非常简单)JavaScript对象。例如,我想:
var obj1 = { food: 'pizza', car: 'ford' }
var obj2 = { animal: 'dog' }
obj1.merge(obj2);
//obj1 now has three properties: food, car, and animal
是否有一种内置的方法来实现这一点?我不需要递归,也不需要合并函数,只需要平面对象上的方法。
当前回答
使用Undercore.js,要合并对象数组,请执行以下操作:
var arrayOfObjects = [ {a:1}, {b:2, c:3}, {d:4} ];
_(arrayOfObjects).reduce(function(memo, o) { return _(memo).extend(o); });
结果是:
Object {a: 1, b: 2, c: 3, d: 4}
其他回答
var firstObject = {
key1 : 'value1',
key2 : 'value2'
};
var secondObject={
...firstObject,
key3 : 'value3',
key4 : 'value4',
key5 : 'value5'
}
console.log(firstObject);
console.log(secondObject);
对象.assign()
ECMAScript 2015(ES6)
这是一项新技术,是ECMAScript 2015(ES6)标准的一部分。这项技术的规范已经定稿,但请查看兼容性表,了解各种浏览器中的用法和实现状态。
assign()方法用于将所有可枚举自身财产的值从一个或多个源对象复制到目标对象。它将返回目标对象。
var o1 = { a: 1 };
var o2 = { b: 2 };
var o3 = { c: 3 };
var obj = Object.assign(o1, o2, o3);
console.log(obj); // { a: 1, b: 2, c: 3 }
console.log(o1); // { a: 1, b: 2, c: 3 }, target object itself is changed.
在一行代码中合并N个对象的财产
Object.assign方法是ECMAScript 2015(ES6)标准的一部分,它完全符合您的需要。(不支持IE)
var clone = Object.assign({}, obj);
assign()方法用于将所有可枚举自身财产的值从一个或多个源对象复制到目标对象。
阅读更多。。。
支持旧浏览器的polyfill:
if (!Object.assign) {
Object.defineProperty(Object, 'assign', {
enumerable: false,
configurable: true,
writable: true,
value: function(target) {
'use strict';
if (target === undefined || target === null) {
throw new TypeError('Cannot convert first argument to object');
}
var to = Object(target);
for (var i = 1; i < arguments.length; i++) {
var nextSource = arguments[i];
if (nextSource === undefined || nextSource === null) {
continue;
}
nextSource = Object(nextSource);
var keysArray = Object.keys(nextSource);
for (var nextIndex = 0, len = keysArray.length; nextIndex < len; nextIndex++) {
var nextKey = keysArray[nextIndex];
var desc = Object.getOwnPropertyDescriptor(nextSource, nextKey);
if (desc !== undefined && desc.enumerable) {
to[nextKey] = nextSource[nextKey];
}
}
}
return to;
}
});
}
**使用Object.assign或排列合并对象很简单。。。操作员**
var obj1={food:“pizza”,car:“ford”}var obj2={animal:“狗”,car:“宝马”}var obj3={a:“a”}var mergedObj=对象赋值(obj1、obj2、obj3)//或使用Spread操作符(…)var mergedObj={…obj1,…obj2,…obj3}console.log(mergedObj);
对象从右向左合并,这意味着与右侧对象具有相同财产的对象将被覆盖。
在此示例中,obj2.car覆盖obj1.car
你应该使用lodash的默认值Deep
_.defaultsDeep({ 'user': { 'name': 'barney' } }, { 'user': { 'name': 'fred', 'age': 36 } });
// → { 'user': { 'name': 'barney', 'age': 36 } }