JS如何对包含多个数值的数组使用reduce

JS How to use reduce on array containing multiple numerical values

本文关键字:数组 reduce 包含多 JS      更新时间:2023-09-26

我有一个这样的数组。

[{
    PropertyOne : 1,
    PropertyTwo : 5
},
{
    PropertyOne : 3,
    PropertyTwo : 5
},...]

我想要一个这样的数组它聚集了这个数组的所有列,最终像这样

[{
    PropertyOne : 4,
    PropertyTwo : 10
}}

如果是单列,我知道我可以使用。reduce,但是我不知道如何使用多列。

var array = [{
  PropertyOne : 1,
  PropertyTwo : 5
},
{
  PropertyOne : 2,
  PropertyTwo : 5
}];
var reducedArray = array.reduce(function(accumulator, item) {
  // loop over each item in the array
  Object.keys(item).forEach(function(key) {
    // loop over each key in the array item, and add its value to the accumulator.  don't forget to initialize the accumulator field if it's not
    accumulator[key] = (accumulator[key] || 0) + item[key];
  });
  return accumulator;
}, {});

使用ES6箭头函数相同(与其他答案相同):

    var reducedArray = array.reduce((accumulator, item) => {
      Object.keys(item).forEach(key => {
        accumulator[key] = (accumulator[key] || 0) + item[key];
      });
      return accumulator;
    }, {});