1

我正在寻找 group by 在二级 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 字符串中的二级数组分组。例如,如果我有以下 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

有人知道我在顶部发布的工作副本的哪一部分需要更改吗?

提前致谢..

4

1 回答 1

0

您可以递归地遍历 javascript 对象。一件棘手的事情是 javascript 对象可以是 json 对象或数组。在我的示例解决方案中,我为它们中的每一个定义了两个不同的 for 循环,可能有一种简单的方法可以做到这一点。无论如何,我的解决方案适用于任何级别的 groupby。这是jsFiddle

于 2012-08-24T03:51:28.623 回答