I need help with grouping at the second level of a JSON string. The code I have works well for one level arrays in the 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
The above example works well for one level array grouping but I'm looking to implement second level array grouping in a JSON string. For example, consider the following JSON string::
{
"Category": {
"old_modi":1,
"new_modi":1,
"FORM": [{
"name":"form1",
"date":"08/08/2012",
"location":"abc",
"PERSON":[{
"ID":1,
"author":"xyz"
}]
}]
}
}
Desired output (Author name grouped by form name, date, and location) ::
xyz
form1 08/08/2012 xyz
If anyone has an idea on how to modify the existing code to achieve this, it would be greatly appreciated.
Thank you in advance..