需要帮助从 JavaScript 中的对象数组中获取计数
Need helping in getting counts out of an array of objects in JavaScript
我正在处理一组看起来像这样的对象:
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);
我正在处理一组看起来像这样的对象:
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);