首页 > 解决方案 > 将字符串在 JSON 数组中的出现求和并将其存储在单独的 JSON 数组中

问题描述

我有一个 JSON 数组,如下所示:

var teamDetails=[ 
 { "pType" : "Search Engines", "value" : 5},
 { "pType" : "Content Server", "value" : 1},
 { "pType" : "Content Server", "value" : 1},
 { "pType" : "Search Engines", "value" : 1},
 { "pType" : "Business", "value" : 1,},
 { "pType" : "Content Server", "value" : 1},
 { "pType" : "Internet Services", "value" : 1},
 { "pType" : "Search Engines", "value" : 6},
 { "pType" : "Search Engines", "value" : 1} 
];

我想动态和单独地计算 ptype 的数量,如果 ptype 发生变化,应该应用它。

Expected output:

var output = [{"label":"Search Engines"},{"Occurance":4},{"label":"Content Server"},{"Occurance":3},{"label":"Business"},{"Occurance":1},{"label":"Internet Services"},{"Occurance":1}];

标签: javascriptjson

解决方案


您可以使用reducethenmap方法首先为 groupBy 创建对象,然后获取对象数组。

var data=[ { "pType" : "Search Engines", "value" : 5},{ "pType" : "Content Server", "value" : 1},{ "pType" : "Content Server", "value" : 1},{ "pType" : "Search Engines", "value" : 1},{ "pType" : "Business", "value" : 1,},{ "pType" : "Content Server", "value" : 1},{ "pType" : "Internet Services", "value" : 1},{ "pType" : "Search Engines", "value" : 6},{ "pType" : "Search Engines", "value" : 1} ];

const obj = data.reduce((r, {pType: label, Occurance}) => {
  if(!r[label]) r[label] = {label, Occurance: 1}
  else r[label].Occurance++;
  return r;
}, {})

const result = [].concat(...Object.values(obj).map(({label, Occurance}) => [{label}, {Occurance}])) 
  
console.log(result)


推荐阅读