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

时间:2018-09-26 01:05:46

标签: javascript arrays

我有以下对象数组

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
  }
}); 

该方法仅适用于我必须添加的每种新型occupation

有没有更简单的解决方案? (纯JavaScript或Lodash向导)

感谢任何输入!

1 个答案:

答案 0 :(得分:5)

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;

但是即使那样,它也会生成“ q A TesterCount”而不是“ q a TesterCount”。一般而言,进一步发展将是一个真正的挑战。