我怎样才能转动这个数组:
[
{ cat: 'Uncategorized', amount: 60 },
{ cat: 'Auto & Transport', amount: 28.01 },
{ cat: 'Auto & Transport', amount: 10.57 },
{ cat: 'Shopping', amount: 7.96 },
{ cat: 'Uncategorized', amount: 100 }
]
进入这个:
[
{ cat: 'Uncategorized', amount: 160},
{ cat: 'Auto & Transport', amount: 38.58 },
{ cat: 'Shopping', amount: 7.96 },
]
其实我想把同一个猫的物品相加
提前致谢
答案 0 :(得分:0)
您可以使用 reduce
const arr = [{
cat: "Uncategorized",
amount: 60
},
{
cat: "Auto & Transport",
amount: 28.01
},
{
cat: "Auto & Transport",
amount: 10.57
},
{
cat: "Shopping",
amount: 7.96
},
{
cat: "Uncategorized",
amount: 100
},
];
const result = arr.reduce((acc, { cat, amount }) => {
const prop = acc.find((o) => o.cat === cat);
if (!prop) {
acc.push({ cat, amount });
} else {
prop.amount += amount;
}
return acc;
}, []);
console.log(result);
答案 1 :(得分:0)
您可以将数组缩减为一个对象,使用 cat
作为键对 amount
求和。然后,使用 Array.values()
:
const unOrgArray = [{"cat":"Uncategorized","amount":60},{"cat":"Auto & Transport","amount":28.01},{"cat":"Auto & Transport","amount":10.57},{"cat":"Shopping","amount":7.96},{"cat":"Uncategorized","amount":100}]
const result = Object.values(unOrgArray.reduce((acc, obj) => {
if(!acc[obj.cat]) // if the object doesn't exist on the accumulator
acc[obj.cat] = { ...obj } // clone the current object
else // if it does exist
acc[obj.cat].amount += obj.amount // add the amount to the sum
return acc
}, {}))
console.log(result)
答案 2 :(得分:0)
您可以使用 Array.reduce 按类别对列表进行分组。
然后使用 Object.entries 和 Array.map 将它们转换为数组
const list = [
{ cat: 'Uncategorized', amount: 60 },
{ cat: 'Auto & Transport', amount: 28.01 },
{ cat: 'Auto & Transport', amount: 10.57 },
{ cat: 'Shopping', amount: 7.96 },
{ cat: 'Uncategorized', amount: 100 }
];
console.log(
Object.entries(
list.reduce((acc, item) => ({ ...acc, [item.cat]: (acc[item.cat] || 0) + item.amount }), {}),
).map((entry) => ({
cat: entry[0],
amount: entry[1],
})),
);