【问题标题】:ES6 spread to merge objects in an array [duplicate]ES6传播以合并数组中的对象[重复]
【发布时间】:2019-10-02 05:51:28
【问题描述】:

如何使用 ES6 扩展运算符合并数组中的对象?假设我们有这样的对象:

    let arr = [{ a: 1, b: true }, { c: "val", d: null }];

结果是这个对象:

    { a: 1, b: true, c: "val", d: null };

【问题讨论】:

    标签: javascript ecmascript-6


    【解决方案1】:

    您可以将元素分散到Object.assign 中,而无需进一步循环。

    let arr = [{ a: 1, b: true }, { c: "val", d: null }],
        result = Object.assign({}, ...arr);
    
    console.log(result);

    【讨论】:

      【解决方案2】:

      Array.prototype.reduce()函数(docs here)。

      let arr = [{ a: 1, b: true }, { c: "val", d: null }];
      let obj = arr.reduce((accumulator, current) => ({...accumulator, ...current}), {});
      console.log(obj);

      与往常一样,从箭头函数返回对象字面量时,不要忘记用参数 (...) 包装返回值,就像 ({...accumulator, ...current}) 一样,以便区分代码块和对象字面量 (docs here)。

      【讨论】:

      • 不必要的冗长。相反,请使用Object.assign({}, ...arr)
      猜你喜欢
      • 1970-01-01
      • 2020-02-23
      • 2016-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-15
      • 1970-01-01
      • 2020-10-20
      相关资源
      最近更新 更多