我有这样的数据样本
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)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句