Javascript 将同一数组内的多个对象合并为一个对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27538349/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Merge multiple objects inside the same array into one object
提问by error123456789
var arrObj = [{a:1, b:2},{c:3, d:4},{e:5, f:6}];
how can i merge this into one obj?
我怎样才能把它合并成一个 obj?
//mergedObj = {a:1, b:2, c:3, d:4, e:5, f:6}
回答by thefourtheye
If your environment supports Object.assign, then you can do the same in a succinct way like this
如果您的环境支持Object.assign,那么您可以像这样以简洁的方式执行相同的操作
const arrObj = [{a: 1, b: 2}, {c: 3, d: 4}, {e: 5, f: 6}];
console.log(arrObj.reduce(function(result, current) {
return Object.assign(result, current);
}, {}));
// If you prefer arrow functions, you can make it a one-liner ;-)
console.log(arrObj.reduce(((r, c) => Object.assign(r, c)), {}));
// Thanks Spen from the comments. You can use the spread operator with assign
console.log(Object.assign({}, ...arrObj));
ES5 solution:
ES5解决方案:
You can use Array.prototype.reducelike this
您可以使用Array.prototype.reduce这样的
var resultObject = arrObj.reduce(function(result, currentObject) {
for(var key in currentObject) {
if (currentObject.hasOwnProperty(key)) {
result[key] = currentObject[key];
}
}
return result;
}, {});
console.log(resultObject);
# { a: 1, b: 2, c: 3, d: 4, e: 5, f: 6 }
This solution, simply gathers all the keys and their values in every object in the result, which is finally returned to us as the result.
这个解决方案,简单地收集 中每个对象中的所有键和它们的值,result最终作为结果返回给我们。
This check
这个检查
if (currentObject.hasOwnProperty(key)) {
is necessary to make sure that we are not including all the inherited enumerable properties in the result.
有必要确保我们没有在结果中包含所有继承的可枚举属性。
回答by Doorknob
You could use reducefor an elegant solution:
您可以使用reduce优雅的解决方案:
arrObj.reduce(function(acc, x) {
for (var key in x) acc[key] = x[key];
return acc;
}, {});
See MDN docs for reducefor more information.
有关更多信息,请参阅MDN 文档reduce。

