按值对 JSON 进行分组
IT技术
javascript
jquery
json
grouping
2021-03-18 05:27:51
1个回答
假设,JSON 输出是
outJSON=
[ {
team: "TeamA",
name: "Ahmed",
field3:"val3"
},
{
team: "TeamB",
name: "Ahmed",
field3:"val43"
},
{
team: "TeamA",
name: "Ahmed",
field3:"val55"
},
]
然后看groupBy
下面DEMO中的功能:
演示:
outJSON= [ {team: "TeamA",name: "Ahmed",field3:"val3"}, {team: "TeamB",name: "Ahmed",field3:"val43"}, {team: "TeamA",name: "Ahmed",field3:"val55"} ]
var groupBy = function(xs, key) {
return xs.reduce(function(rv, x) {
(rv[x[key]] = rv[x[key]] || []).push(x);
return rv;
}, {});
};
var groubedByTeam=groupBy(outJSON, 'team')
console.log(groubedByTeam);
然后,如果您想遍历类别(团队),请获取数组中的所有类别:
Object.keys(groubedByTeam) // return ["TeamA","TeamB"]
然后 :
Object.keys(groubedByTeam).forEach(function(category){
console.log(`Team ${category} has ${groubedByTeam[category].length} members : `);
groubedByTeam[category].forEach(function(memb,i){
console.log(`---->${i+1}. ${memb.name}.`)
})
});