Summarize And Group Json Object In Jquery
I am having problems summarizing and grouping my object in Jquery as I would like to group by country and then have a grand total based on subperiods 4,5,and 6 for values within co
Solution 1:
This should do the trick:
g_jsonData.reduce(function(out, curr){
// Make sure the current country exists on the output object.// Then add the current object's col1 to the current country's subperiod,// checking to see if the current subperiod exists. Also, cast the `col1` to int `(+curr.col1)`out.countries[curr.Country] = out.countries[curr.Country] || {};
out.countries[curr.Country][curr.Subperiod] = (out.countries[curr.Country][curr.Subperiod] || 0) + (+curr.col1);
// And add it to the total, too.out.columns[curr.Subperiod] = (out.columns[curr.Subperiod] || 0) + (+curr.col1);
// Count occurencesout.count[curr.Country] = out.count[curr.Country] || {};
out.count[curr.Country][curr.Subperiod] = (out.count[curr.Country][curr.Subperiod] || 0) + 1;
returnout;
},
{'columns':{},'countries':{},'count':{}}); // second parameter to `reduce` is a default object, in this case: `{'columns':{},'countries':{},'count':{}}}`
Returns:
{
"columns": {
"4": 475,
"5": 225,
"6": 500.75
},
"countries": {
"Spain": {
"4": 175,
"5": 125,
"6": 300.75
},
"France": {
"4": 300,
"5": 100,
"6": 200
}
},
"count": {
"Spain": {
"4": 3,
"5": 1,
"6": 2
},
"France": {
"4": 3,
"5": 1,
"6": 2
}
}
}
Please note this doesn't changeg_jsonData
, it only returns the new object.
To use the new object, you have to assign it to a variable, of course:
var output = g_jsonData.reduce(func....);
You could make the code a little shorter (/easier to look at) like this:
g_jsonData.reduce(function(out, curr){
var c = curr.Country,
s = curr.Subperiod,
v = +curr.col1; //value cast to int alreadyout.countries[c] = out.countries[c] || {};
out.countries[c][s] = (out.countries[c][s] || 0 ) + v;
out.count[c] = out.count[c] || {};
out.count[c][s] = (out.count[c][s] || 0 ) + 1;
out.columns[s] = (out.columns[s] || 0 ) + v;
returnout;
},
{'columns':{},'countries':{},'count':{}});
Now it's relatively easy to make col1
a variable name.
Replace:
v = +curr.col1;
With:
v = +curr['col1'];
Or:
v = +curr[someVariable];
Post a Comment for "Summarize And Group Json Object In Jquery"