簡體   English   中英

計算對象數組中的不同屬性

[英]Count the Distinct Properties in an Array of Objects

我有以下對象的數組

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向導)

任何輸入表示贊賞!

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”。 一般而言,進一步發展將是一個真正的挑戰。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM