我正在寻找group by来执行第二级JSON字符串。例如,我正在使用下面的代码来使用组,它可以很好地工作在JSON字符串内有1级数组的地方。在第二级数组JSON上分组
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字符串分组。对于一个例子,如果我有以下的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
任何人有任何想法,这我发布在顶部的工作副本部分需要更改?
在此先感谢..
你的意思是“JavaScript对象”?因为我没有看到任何JSON字符串。 – gilly3
是的,我的意思是javascript对象。 –