[
{
"assetNo":"51GQA21AP001"
},
{
"assetNo":"51GQA22AP001"
},
{
"assetNo":"51GQA24AP001"
},
{
"assetNo":"51GQA22AP001"
},
{
"assetNo":"51GQA21AP001"
},
{
"assetNo":"51GQA23AP001"
},
{
"assetNo":"51GQA24AP001"
}
]
我需要以下输出:
[{
"assetNo": "51GQA21AP001",
"count": 2
}, {
"assetNo": "51GQA22AP001",
"count": 2
}, , {
"assetNo": "51GQA23AP001",
"count": 2
},{
"assetNo": "51GQA24AP001",
"count": 1
}]
答案 0 :(得分:1)
在这里:
var data = [
{
"assetNo":"51GQA21AP001"
},
{
"assetNo":"51GQA22AP001"
},
{
"assetNo":"51GQA24AP001"
},
{
"assetNo":"51GQA22AP001"
},
{
"assetNo":"51GQA21AP001"
},
{
"assetNo":"51GQA23AP001"
},
{
"assetNo":"51GQA24AP001"
}
]
let count = {};
data.forEach(el => {
count[el.assetNo] = count[el.assetNo] ? count[el.assetNo]+1 : 1;
})
let lastResult = [];
for (var key in count) {
lastResult.push({ assetNo : key , count : count[key] });
}
console.log(lastResult);

答案 1 :(得分:1)
您可以使用array#reduce
根据assetNo
对数组进行分组。
var data = [{ "assetNo": "51GQA21AP001" }, { "assetNo": "51GQA22AP001" }, { "assetNo": "51GQA24AP001" }, { "assetNo": "51GQA22AP001" }, { "assetNo": "51GQA21AP001" }, { "assetNo": "51GQA23AP001" }, { "assetNo": "51GQA24AP001" } ],
result = Object.values(data.reduce((r,o) => {
r[o.assetNo] = r[o.assetNo] || {assetNo : o.assetNo, count : 0};
r[o.assetNo].count += 1;
return r;
},{}));
console.log(result);