I am looking for group by to perform at second level JSON string. For example i am using the below code to use group by it works pefrectly fine where there is 1 level of array inside JSON string.
Array.prototype.groupBy = function(keyName) {
var res = {};
this.forEach(function(x) {
var k = x[keyName];
var v = res[k];
if (!v) v = res[k] = [];
v.push(x);
});
return res;
};
var myObject = {
"groups": [{
"id": "2",
"name": "test group 1",
"category": "clinical note",
"author": "RRP"
}, {
"id": "1",
"name": "test group 2",
"category": "clinical image",
"author": "LKP"
}, {
"id": "2",
"name": "test group 1",
"category": "clinical document",
"author": "RRP"
}, {
"id": "4",
"name": "test group 4",
"category": "clinical note",
"author": "John"
}]
}
myObject.groups.sort(function(a,b) { return a.author > b.author } );
var byJob = myObject.groups.groupBy('id');
for (var author in byJob) {
document.write('<h3>'+author+','+byJob[author].length+'</h3>');
byJob[author].forEach(function(e) {
document.write('<p>'+e.id +', '+e.name+'</p>');
});
Output::
1,1
1, test group 2
2,2
2, test group 1
2, test group 1
4,1
4, test group 4
Now the above example works perfectly fine but i am looking for second level array grouping in JSON string. For a example if i have following JSON string::
{
"Category": {
"old_modi":1,
"new_modi":1,
"FORM": [{
"name":"form1",
"date":"08/08/2012",
"location":"abc",
"PERSON":[{
"ID":1,
"author":"xyz"
}]
}]
}
}
Would expect output (Author name would be group by its form name,date and location) ::
xyz
form1 08/08/2012 xyz
Anybody have any idea which portion of the working copy which i posted in top need to change?
Thanks in advance..
You can iterate through the javascript object recursively. One tricky thing is the javascript object can either be a json object or an array. In my sample solution, I had two different for-loop defined for each of them, there might be a easy way to do that. Anyway, my solution works for any level of groupby. here is the jsFiddle