【问题标题】:Merge multiple objects inside the same array into one object [duplicate]将同一数组中的多个对象合并为一个对象[重复]
【发布时间】:2015-02-16 18:06:28
【问题描述】:
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}

【问题讨论】:

  • const mergeObj = arrObj.reduce((r,c) => ({...r,...c}), {})
  • Object.assign(...arrObj)

标签: javascript arrays object


【解决方案1】:

如果你的环境支持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)) {

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

【讨论】:

  • 我们可以通过调用Object.assignapply 来完全避免使用reduce。 Object.assign.apply( null, objects );
  • 或者,使用扩展运算符:Object.assign( ...arrObj )
  • @Spen 谢谢。我已将您的建议也包含在答案中。
  • @Spen 仅供参考,Object.assign(...arrObj) 改变数组的第一个元素。所以,应该是:Object.assign({}, ...arrObj)
  • Object.assign({}, [{one: 1},{two: 2}, {three:3}]) ,我觉得这很有帮助,对我很有用。跨度>
【解决方案2】:

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

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

MDN docs for reduce for more information

【讨论】:

    猜你喜欢
    • 2021-11-12
    • 1970-01-01
    • 1970-01-01
    • 2018-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-24
    相关资源
    最近更新 更多