第 2 レベルの JSON 文字列で実行するグループ化を探しています。たとえば、以下のコードを使用して group by を使用しています。これは、JSON 文字列内に 1 レベルの配列がある場合に完全に正常に機能します。
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>');
});
出力::
1,1
1, test group 2
2,2
2, test group 1
2, test group 1
4,1
4, test group 4
上記の例は完全に正常に機能しますが、JSON 文字列でグループ化された第 2 レベルの配列を探しています。たとえば、次の JSON 文字列がある場合::
{
"Category": {
"old_modi":1,
"new_modi":1,
"FORM": [{
"name":"form1",
"date":"08/08/2012",
"location":"abc",
"PERSON":[{
"ID":1,
"author":"xyz"
}]
}]
}
}
出力が期待されます (作成者名はフォーム名、日付、および場所によってグループ化されます) ::
xyz
form1 08/08/2012 xyz
一番上に投稿した作業コピーのどの部分を変更する必要があるか、誰にも分かりますか?
前もって感謝します..