3

JSONデータがあり、group byのようなことをする必要があり、ここで前にこの質問をしましたが、満足のいく答えが得られないので、今回はさらに詳しく説明したいと思います。

groupbyまず、SQLのようにjavascriptとの違いを誰かが説明できますか?orderbyを使用するために必要な集計関数を実行しますgroup by。しかし、集計関数のようなものは必要ありません。ここでは、私が探していた非常にサンプルのJSONデータと出力を提供します。

すべての作成者名はsortby英数字順にする必要があります。

JSONデータ:

var myObject = {
    "Apps": [
        {
            "Name": "app1",
            "id": "1",
            "groups": [
                {
                    "id": "1",
                    "name": "test group 1",
                    "category": "clinical note",
                    "author": "RRP"
                }, {
                    "id": "2",
                    "name": "test group 2",
                    "category": "clinical image",
                    "author": "LKP"
                }, {
                    "id": "3",
                    "name": "test group 3",
                    "category": "clinical document",
                    "author": "RRP"
                }, {
                    "id": "4",
                    "name": "test group 4",
                    "category": "clinical note",
                    "author": "John"
                }
            ]
        }
    ]
}

期待される出力:

John
  4 testgroup4 clinicalnote 
RRP
  1 testgroup1  clinicalnote
  3 testgroup3  clinicaldocument
LKP
  2 testgroup2 clinicalimage    

どんなアイデア/提案/方向性/考えも大いに役立ちます。

4

3 に答える 3

3

Underscore.jsを使えば簡単にできます:

_.chain(myObject.Apps[0].groups).sortBy("author").groupBy("author").value();

JSON オブジェクトを出力します。

{
 "John":[{"id":"4","name":"test group 4","category":"clinical note","author":"John"}],
 "LKP":[{"id":"2","name":"test group 2","category":"clinical image","author":"LKP"}],
 "RRP":[{"id":"1","name":"test group 1","category":"clinical note","author":"RRP"},{"id":"3","name":"test group 3","category":"clinical document","author":"RRP"}]
}
于 2014-02-09T07:55:05.777 に答える
1

このシナリオでは、Javascript に組み込みの「group by」または「order by」はありません。これは手動で行う必要があります。このようなものが役立つかもしれません:

var groups = myObject.Apps[0].groups;
var authors = {};
var authorNames = [];

for(var i = 0; i < groups.length; i++) {
    var group = groups[i];    

    if(typeof authors[group.author] === "undefined") {
        authors[group.author] = [];
        authorNames.push(group.author);
        authorNames.sort();
    }

    authors[group.author].push({
        id: group.id,
        name: group.name,
        category: group.category
    });       
}

通常、連想配列では、キーの順序はあまり気にしません。反復処理中は、通常、順序は保証されません。ここで行っているのは、ソートされた順序で名前の個別の配列を維持することです。次に、その配列を繰り返し処理し、それらの値を使用して、関連付けられたオブジェクトを連想配列から取得します。

フィドルをチェックしてください。

于 2012-06-18T21:01:14.077 に答える