Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grouping JSON by values

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, like the Shopify careers page.

Here is the codepen and here is the JSON

I tried adding the following on line 38 of the codepen to try to grab the team values, but it's not outputting as expected (I'm getting one letter per line, which isn't helpful):

for (var x in _data[i].postings[j].categories.team)

I'm sure it's probably something super simple, but I'm definitely not a javascript guy. Any help would be much appreciated!

like image 501
robotsmeller Avatar asked Jul 25 '16 19:07

robotsmeller


People also ask

What is [] and {} in JSON?

' { } ' used for Object and ' [] ' is used for Array in json.

How do you sort data in JSON?

Using json. dumps() function is one way to sort the JSON object. It is used to convert the array of JSON objects into a sorted JSON object. The value of the sort_keys argument of the dumps() function will require to set True to generate the sorted JSON objects from the array of JSON objects.

How are values separated in JSON?

JSON has the following syntax. Objects are enclosed in braces ( {} ), their name-value pairs are separated by a comma ( , ), and the name and value in a pair are separated by a colon ( : ). Names in an object are strings, whereas values may be of any of the seven value types, including another object or an array.

Are [] valid in JSON?

[] is a valid JSON which is an empty array.


1 Answers

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}.`)
    })
});
like image 86
Abdennour TOUMI Avatar answered Oct 13 '22 14:10

Abdennour TOUMI