gpt4 book ai didi

javascript - 计算 JavaScript 对象中每个类别中的项目数

转载 作者:行者123 更新时间:2023-12-03 23:19:59 26 4
gpt4 key购买 nike

我有一个包含数百个对象的数组,每个对象都有一个类别。我希望返回一个对象,该对象列出了每个类别的项目数的类别。

const arr = [
{id: 1, name: 'ford', category: 'vehicle'},
{id: 2, name: 'pig', category: 'animal'},
{id: 3, name: 'dog', category: 'animal'},
{id: 4, name: 'chev', category: 'vehicle'},
{id: 5, name: 'cat', category: 'animal'},
{id: 6, name: 'jeep', category: 'vehicle'},
{id: 7, name: 'honda', category: 'vehicle'}
]
我将如何遍历对象并创建一个仅包含两个类别以及每个类别有多少的新对象?
期望的输出:
{vehicle: 4, animal: 3}
代码:

const arr = [
{id: 1, name: 'ford', category: 'vehicle'},
{id: 2, name: 'pig', category: 'animal'},
{id: 3, name: 'dog', category: 'animal'},
{id: 4, name: 'chev', category: 'vehicle'},
{id: 5, name: 'cat', category: 'animal'},
{id: 6, name: 'jeep', category: 'vehicle'},
{id: 7, name: 'honda', category: 'vehicle'}
]

const final = {};
arr.forEach((v) => {
const tst = v.category;
console.log(tst);
if (tst in final){
console.log('found one');
}
});

//console.log(final);

最佳答案

您可以使用减少

const arr = [
{id: 1, name: 'ford', category: 'vehicle'},
{id: 2, name: 'pig', category: 'animal'},
{id: 3, name: 'dog', category: 'animal'},
{id: 4, name: 'chev', category: 'vehicle'},
{id: 5, name: 'cat', category: 'animal'},
{id: 6, name: 'jeep', category: 'vehicle'},
{id: 7, name: 'honda', category: 'vehicle'}
]


const categories = arr.reduce((acc, cur) => {
acc[cur.category] = (acc[cur.category] || 0) + 1
return acc;
}, {})

console.log(categories)

关于javascript - 计算 JavaScript 对象中每个类别中的项目数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65385556/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com