Grouping JSON by values

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:


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);

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}.`)
    })
});

Leave a Comment