[英]How to get array of objects with unique values?
How to sum object array with the same key value? 如何对具有相同键值的对象数组求和?
I have this array: 我有这个数组:
let arrData = [{ category: "Main Expenses", amount: 420 },
{ category: "Food", amount: 50 },
{ category: "Main Expenses", amount: 4530},
{ category: "Food", amount: 4520 },
{ category: "Main Expenses", amount: 4530 },
{ category: "Food", amount: 450 },
{ category: "Self Care", amount: 7540 },
{ category: "Child Care", amount: 4570 }]
And I need to get array with unique categories, like this: 我需要获得具有唯一类别的数组,如下所示:
[Main Expenses: 9480,
Food: 5020,
Self Care: 7540,
Child Care: 4570]
The expected output is in array is not possible since array will not support key & value pair. 由于数组不支持键值对,因此无法在数组中获得预期的输出。 You may opt for object.
您可以选择对象。
You can use reduce and check if the object contains the key
by category name. 您可以使用reduce并按类别名称检查对象是否包含
key
。 If so then add the amount otherwise create key by the category name and set its value to the amount 如果是这样,则添加金额,否则按类别名称创建键并将其值设置为金额
let arrData = [{ category: "Main Expenses", amount: 420 }, { category: "Food", amount: 50 }, { category: "Main Expenses", amount: 4530 }, { category: "Food", amount: 4520 }, { category: "Main Expenses", amount: 4530 }, { category: "Food", amount: 450 }, { category: "Self Care", amount: 7540 }, { category: "Child Care", amount: 4570 } ] let newData = arrData.reduce((acc, item) => { acc[item.category] = acc[item.category] ? acc[item.category] + item.amount : item.amount; return acc; }, {}); console.log(newData)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.