javascript - 将字符串在 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}];
解决方案
您可以使用reduce
thenmap
方法首先为 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)
推荐阅读
- 64-bit - MFT 记录中的最大数据运行字节数是多少?
- vuejs2 - Vuejs - @click 不触发方法
- android - java.lang.IllegalStateException: 序列化时数据占用不能超过10240字节
- angular - Angular 5:在模态 ng-template 验证中带有 Form 的组件
- python - 询问在 python 中使用 init 的一些技巧
- json - 将嵌套的 JSON 响应转换为 CSV 表
- sql - 在节点js中将数据从txt文件写入数据库
- ms-word - 具有相同自定义功能区组的多个加载项
- mysql - mySQL 部分参与
- angular - rxjs:结合可观察的结果,同时已经用异步管道显示第一个