对数组对象进行分组和求和

Grouping and summing array objects

我有这样的数据样本

   this.userData = [
      {id:1, category: 'Food', amount: 30, pDate: '2021-01-13', description: 'test desc'},
      {id:2, category: 'Fuel', amount: 10, pDate: '2021-01-12', description: 'test desc'},
      {id:3, category: 'Food', amount: 70, pDate: '2021-01-14', description: 'test desc'},
    ]

我想通过这些数据实现的是将它分组并汇总起来,这样就出来了

[
{name: Food, total: 100},
{name: Fuel, total: 30}
]

我当前的代码是什么,我没有得到我想要的输出。

const data = this.userData;
const groups = data.reduce((groups, item) => ({
  ...groups,
  [item.category]: [...(groups[item.category] || []), item]
}), {});
console.log(groups);

试试这个

const userData = [
      {id:1, category: 'Food', amount: 30, pDate: '2021-01-13', description: 'test desc'},
      {id:2, category: 'Fuel', amount: 10, pDate: '2021-01-12', description: 'test desc'},
      {id:3, category: 'Food', amount: 70, pDate: '2021-01-14', description: 'test desc'},
    ]

const hashMap = {}

for (const { category, amount } of userData) {
  if (hashMap[category]) {
    hashMap[category].total += amount
  } else {
   hashMap[category] = { name: category, total: amount }
  }
}

const output = Object.values(hashMap)
console.log(output)

您可以对对象进行分组并获取值。

const
    userData = [{ id:1, category: 'Food', amount: 30, pDate: '2021-01-13', description: 'test desc' }, { id:2, category: 'Fuel', amount: 10, pDate: '2021-01-12', description: 'test desc' }, { id:3, category: 'Food', amount: 70, pDate: '2021-01-14', description: 'test desc' }],
    groups = Object.values(userData.reduce((r, o) => {
        (r[o.category] ??= { name: o.category, total: 0 }).total += o.amount;
        return r;
    }, {}))

console.log(groups);