我正在处理一个对象数组,它看起来像这样。
const fruits = [
{
Fruit: Apple,
Count: 4
},
{
Fruit: Orange,
Count: 3
},
{
Fruit: Apple,
Count: 2
}
]
我想让我的数组看起来像这样:
const fruits = [
{
Fruit: Apple,
Count: 6
},
{
Fruit: Orange,
Count: 3
},
]
有什么办法可以解决这个问题吗?我试过使用Reduce,但不用说,Reduce是我在JavaScript中最大的弱点。我看了很多文章,得到了一个接近的答案,但没有任何文章可以完全帮助我。谢谢你的帮助。
这里是... reduce
的解决方案。
const fruits = [
{
Fruit: "Apple",
Count: 4
},
{
Fruit: "Orange",
Count: 3
},
{
Fruit: "Apple",
Count: 2
}
]
let result = fruits.reduce((acc,current) => {
let obj = acc.find(x => x.Fruit === current.Fruit);
if(!obj){
acc.push({ Fruit: current.Fruit, Count: current.Count });
} else {
obj.Count += current.Count;
}
return acc;
}, []);
console.log(result);
基本上你需要建立一个新的数组(acc
),如果没有这样的项目,就添加一个新的项目。Fruit
或增加计数器。
const fruits = [{
Fruit: "Apple",
Count: 4
},
{
Fruit: "Orange",
Count: 3
},
{
Fruit: "Apple",
Count: 2
}
];
// c => current value
// n => next value
const asObject = fruits.reduce((c, n) => ({ ...c,
[n.Fruit]: (c[n.Fruit] || 0) + n.Count
}), {});
const result = Object.entries(asObject).map(([k, v]) => ({
Fruit: k,
Count: v
}));
console.log(asObject);
console.log(result);