将同一数组中的多个对象合并为一个对象

时间:2014-12-18 02:32:03

标签: javascript arrays object

var arrObj = [{a:1, b:2},{c:3, d:4},{e:5, f:6}];

如何将其合并为一个obj?

//mergedObj = {a:1, b:2, c:3, d:4, e:5, f:6}

2 个答案:

答案 0 :(得分:30)

如果您的环境支持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解决方案:

您可以像这样使用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 }

此解决方案只是收集result中每个对象中的所有键及其值,最后将其作为结果返回给我们。

此检查

if (currentObject.hasOwnProperty(key)) {

是必要的,以确保我们不在结果中包含所有继承的可枚举属性。

答案 1 :(得分:14)

您可以使用reduce获得优雅的解决方案:

arrObj.reduce(function(acc, x) {
    for (var key in x) acc[key] = x[key];
    return acc;
}, {});

请参阅MDN docs for reduce for more information