Grouping JSON by values

前端 未结 1 1760
盖世英雄少女心
盖世英雄少女心 2020-12-05 05:56

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

相关标签:
1条回答
  • 2020-12-05 06:31

    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}.`)
           })
      }); 
    
    0 讨论(0)
提交回复
热议问题