gpt4 book ai didi

javascript - 计算对象数组中的不同属性

转载 作者:行者123 更新时间:2023-11-30 08:21:42 25 4
gpt4 key购买 nike

我有以下对象数组

const users = [
{ name: 'Bob Johnson', occupation: 'Developer' },
{ name: 'Joe Davidson', occupation: 'QA Tester' },
{ name: 'Kat Matthews', occupation: 'Developer' },
{ name: 'Ash Lawrence', occupation: 'Developer' },
{ name: 'Jim Powers', occupation: 'Project Manager}]

我想创建一个对象来存储不同类型occupations 的唯一计数,就像这样

{ developerCount: 3, qaTesterCount: 1, projectManagerCount: 1 }

我目前的解决方案是这种冗长的方法

let occupationCounts = {
developerCount: 0,
qaTesterCount: 0,
projectManagerCount: 0
}

// Loop through the array and count the properties
users.forEach((user) => {
switch(user.occupation){
case 'Developer':
occupationCounts.developerCount++;
break;
// and so on for each occupation
}
});

此方法只会随着我必须添加的每种新类型的职业而增长。

有没有更简单的解决方案? (纯 javascript 或 Lodash 魔法)

欢迎任何意见!

最佳答案

Array.prototype.reduce在这里应该有所帮助,只要您不拘泥于特定的计数名称:

const users = [
{ name: 'Bob Johnson', occupation: 'Developer' },
{ name: 'Joe Davidson', occupation: 'QA Tester' },
{ name: 'Kat Matthews', occupation: 'Developer' },
{ name: 'Ash Lawrence', occupation: 'Developer' },
{ name: 'Jim Powers', occupation: 'Project Manager'}
]

const counts = users.reduce((counts, {occupation}) => {
counts[occupation] = (counts[occupation] || 0) + 1;
return counts
}, {})

console.log(counts)

虽然您可以更改这些名称,但除非真的很重要,否则我不会费心。

编辑

如果你真的想要那些,你可以通过这样的方式接近:

const key = occupation[0].toLowerCase() +
occupation.slice(1).replace(/\s/g, '') + 'Count'
counts[key] = (counts[key] || 0) + 1;

但即使那样生成“qATesterCount”而不是“qaTesterCount”。要做到更进一步将是一个真正的挑战。

关于javascript - 计算对象数组中的不同属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52508557/

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