Using the Lever job posting API, I\'m getting JSON results sorted by location, and I\'m trying to figure out how to group all those results by \"team\" within the results, l
Assume , the JSON output is
outJSON=
[ {
team: "TeamA",
name: "Ahmed",
field3:"val3"
},
{
team: "TeamB",
name: "Ahmed",
field3:"val43"
},
{
team: "TeamA",
name: "Ahmed",
field3:"val55"
},
]
Then see the groupBy
function in the DEMO below:
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);
Then , if you want to loop through categories (teams), get all categories in array :
Object.keys(groubedByTeam) // return ["TeamA","TeamB"]
then :
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}.`)
})
});