猿问

在对象数组中按特定键计算分组值

我有以下数据:


const data2 = [

{

  App: "testa.com",

  Name: "TEST A",

  Category: "HR", 

  Employees: 7

},

{

  App: "testd.com",

  Name: "TEST D",

  Category: "DevOps", 

  Employees: 7

},

{

  App: "teste.com",

  Name: "TEST E",

  Category: "DevOps", 

  Employees: 7

},

{

  App: "testf.com",

  Name: "TEST F",

  Category: "Business", 

  Employees: 7

}

]

我想获得不同类别的数量:现在我正在获得所有不同类别的列表,但我无法计算它们的数量。


以下片段给我不同的类别:


  let uniqueCategory = [];

  for(let i = 0; i < result.data.length; i++){    

      if(uniqueCategory.indexOf(result.data[i].Category) === -1){

        uniqueCategory.push(result.data[i].Category);        

      }        

  }

我应该进行哪些更改才能获得这些类别的计数uniqueCategory- 如下所示:


uniqueCategory = [

  {Category: "DevOps", count: 5},

  {Category: "Business", count: 4},

  ....

  {}

]


holdtom
浏览 103回答 3
3回答

慕婉清6462132

您的方法意味着在-loop.indexOf()的每次迭代中循环您的源数组(使用)。for(..这将减慢不必要的查找过程。相反,您可以使用Array.prototype.reduce()遍历源数组并构建 ,将Map所需Category格式的键和对象作为值,然后提取Map.prototype.values()到结果数组中。这将执行得更快并且扩展性更好。const src = [{App:"testa.com",Name:"TEST A",Category:"HR",Employees:7},{App:"testd.com",Name:"TEST D",Category:"DevOps",Employees:7},{App:"teste.com",Name:"TEST E",Category:"DevOps",Employees:7},{App:"testf.com",Name:"TEST F",Category:"Business",Employees:7}],&nbsp; &nbsp; &nbsp; result = [...src&nbsp; &nbsp; &nbsp; &nbsp; .reduce((r, {Category}) => {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; const cat = r.get(Category)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; cat ? cat.count ++ : r.set(Category, {Category, count: 1})&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return r&nbsp; &nbsp; &nbsp; &nbsp; }, new Map)&nbsp; &nbsp; &nbsp; &nbsp; .values()&nbsp; &nbsp; &nbsp; ]&nbsp; &nbsp;&nbsp;console.log(result).as-console-wrapper{min-height:100%;}

繁花不似锦

最简单的方法是使用Array.prototype.reduceconst arr = [ ... ];const output = arr.reduce((result, obj) => {&nbsp; if (!result[obj.category]) {&nbsp; &nbsp; result[obj.category] = 0;&nbsp; }&nbsp; result[obj.category]++;&nbsp; return result;}, {});console.log(output); // this should log the similar output you want

噜噜哒

.map这是使用and的另一种选择Set:const src = [{&nbsp; App: "testa.com",&nbsp; Name: "TEST A",&nbsp; Category: "HR",&nbsp;&nbsp; Employees: 7},{&nbsp; App: "testd.com",&nbsp; Name: "TEST D",&nbsp; Category: "DevOps",&nbsp;&nbsp; Employees: 7},{&nbsp; App: "teste.com",&nbsp; Name: "TEST E",&nbsp; Category: "DevOps",&nbsp;&nbsp; Employees: 7},{&nbsp; App: "testf.com",&nbsp; Name: "TEST F",&nbsp; Category: "Business",&nbsp;&nbsp; Employees: 7}];const categories = src.map(obj => obj.Category);const distinctCategories = [...new Set(categories)];console.log(distinctCategories.length);
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答