3

我正在获取一个包含一组对象的对象,并且我正在尝试遍历它们以通过 id 引用对数据求和。

如果我有这样的功能,这可能比解释更容易展示......

let projectArray = this.projects
    projectArray.forEach(function (el) {
        console.log(el.categoriesTotal)
    })

我得到了一个很好的返回包含我所追求的对象的数组,看起来像这样......

[
  { _id: 6, total: 4478.4 },
  { _id: 1, total: 110248.13 },
  { _id: 7, total: 663695.1 }
]
[
  { _id: 7, total: 31278 },
  { _id: 1, total: 67174.66 },
  { _id: 4, total: 3712.8 },
  { _id: 8, total: 670 }
]
...

我想要做的是通过 id 引用返回总和,例如

_id: 1, total: 177422.79,
_id: 6, total: 4478.4

我认为我想要的方法是“减少”,但我尝试遵循这个答案,但我收到一个错误,告诉我“减少不是函数”,可能是因为我试图“减少”多个数组.

如何从这些数组返回总和?

4

3 回答 3

1

您应该能够使用Array.flat()来展平数组,然后使用reduce来获得所需的结果,例如

let a = [[
  { _id: 6, total: 4478.4 },
  { _id: 1, total: 110248.13 },
  { _id: 7, total: 663695.1 }
],
[
  { _id: 7, total: 31278 },
  { _id: 1, total: 67174.66 },
  { _id: 4, total: 3712.8 },
  { _id: 8, total: 670 }
]];

let result = Object.values(a.flat().reduce((map, r) => { 
    if (!map[r._id]) map[r._id] = { _id: r._id, total: 0};
    map[r._id].total += r.total;
    return map;
}, {}));

console.log(result);

于 2020-04-08T08:10:17.113 回答
1

您可以使用Array.prototype.flat来展平您的数组数组,然后只是reduce聚合总和。

var projectArray = [[
  { _id: 6, total: 4478.4 },
  { _id: 1, total: 110248.13 },
  { _id: 7, total: 663695.1 }
],
[
  { _id: 7, total: 31278 },
  { _id: 1, total: 67174.66 },
  { _id: 4, total: 3712.8 },
  { _id: 8, total: 670 }
]];

var result = projectArray.flat().reduce( (acc,i) => {
   if(acc.hasOwnProperty(i._id))
       acc[i._id] += i.total;
   else
       acc[i._id] = i.total;
   return acc;
},{});
console.log(result);

于 2020-04-08T08:14:51.063 回答
1

const data = [
  [
    { _id: 6, total: 4478.4 },
    { _id: 1, total: 110248.13 },
    { _id: 7, total: 663695.1 }
  ],
  [
    { _id: 7, total: 31278 },
    { _id: 1, total: 67174.66 },
    { _id: 4, total: 3712.8 },
    { _id: 8, total: 670 }
  ]
];

let temp = {};
data.forEach( arrayOfObjects => {
  arrayOfObjects.forEach( obj => {
    if(temp[obj._id] != null) {
      temp[obj._id] += obj.total
    }else{
      temp[obj._id] = obj.total
    }
  })
})
let result = [];
for ( [key,value] of Object.entries(temp) ){
  result.push({ _id: key*1, total: value })
}

console.log(result)

于 2020-04-08T08:20:04.097 回答