[英]How to sum up values of same field in array of objects?
我有一个对象数组
const data = [
{ category: 'shopping', amount: 50 },
{ category: 'rent', amount: 1000 },
{ category: 'groceries', amount: 20 },
{ category: 'shopping', amount: 50 }
]
我正在尝试总结每个类别的金额
const result = [
{ category: 'shopping', amount: 100 },
{ category: 'rent', amount: 1000 },
{ category: 'groceries', amount: 20 }
]
到目前为止,我正在考虑删除类别的“重复项”并将它们存储到一个数组中
const temp = data.map((obj) => {
return obj.category
})
const categories = [...new Set(temp)] // ['shopping','rent','groceries']
有了以上内容,我正在考虑做一个嵌套循环,但经过多次尝试,我失败了。
任何帮助表示赞赏
您可以使用reduce()来做到这一点。
迭代给定数据,如果存在与当前项目具有相同category
的项目,则添加amount
,否则将当前项目添加为新条目。
const data = [ { category: 'shopping', amount: 50 }, { category: 'rent', amount: 1000 }, { category: 'groceries', amount: 20 }, { category: 'shopping', amount: 50 } ]; let result = data.reduce((acc, curr) => { let item = acc.find(item => item.category === curr.category); if (item) { item.amount += curr.amount; } else { acc.push(curr); } return acc; }, []); console.log(result);
这是使用 object 作为累加器的替代方法。 这具有性能优势,因为我们不必在每次迭代时调用find()
。 感谢frodo2975的建议。
const data = [ { category: 'shopping', amount: 50 }, { category: 'rent', amount: 1000 }, { category: 'groceries', amount: 20 }, { category: 'shopping', amount: 50 } ]; let result = Object.values(data.reduce((acc, curr) => { let item = acc[curr.category]; if (item) { item.amount += curr.amount; } else { acc[curr.category] = curr; } return acc; }, {})); console.log(result);
我将专注于有效计算每个类别的总数,然后以您需要的格式重组数据。 所以是这样的:
// Construct an object mapping category to total amount.
const totals = data.reduce((totals, { category, amount }) => {
totals[category] = (totals[category] || 0) + amount;
}, {});
// Format the data as you like.
const result = Object.entries(totals).map(([category, amount]) => ({ category, amount });
只是使用reduce
方法的另一个版本:)
const data = [ { category: 'shopping', amount: 50 }, { category: 'rent', amount: 1000 }, { category: 'groceries', amount: 20 }, { category: 'shopping', amount: 50 } ]; const result = data.reduce((a,c) => { a[c.category] = a[c.category] || {category: c.category, amount: 0}; a[c.category].amount += c.amount; return a; }, {}) console.log(Object.values(result));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.