使用jQuery按JSON数组分组

时间:2015-06-17 13:52:46

标签: javascript jquery arrays grouping

我有一组JSON数组,我希望结果按“Id”列分组。我不会使用underscore.js,因为这不能在我们的项目中使用。唯一的选择是使用jQuery。我的源数组和预期结果如下。

var origObj = [{ "Id": "1", "name": "xxx", "age": "22" },
               { "Id": "1", "name": "yyy", "age": "15" },
               { "Id": "5", "name": "zzz", "age": "59" }]

var output = [{"1": [{ "Id": "1", "name": "xxx", "age": "22" },
                     { "Id": "1", "name": "yyy", "age": "15" }],
               "5": [{ "Id": "5", "name": "zzz", "age": "59" }]}]

2 个答案:

答案 0 :(得分:10)

您可以使用Array.prototype.reduce完成此操作。查看此帖子了解更多详情https://stackoverflow.com/a/22962158/909535扩展您需要的内容

var data= [{ "Id": "1", "name": "xxx", "age": "22" },
        { "Id": "1", "name": "yyy", "age": "15" },
        { "Id": "5", "name": "zzz", "age": "59" }];
        console.log(data.reduce(function(result, current) {
            result[current.Id] = result[current.Id] || [];
            result[current.Id].push(current);
            return result;
        }, {}));

答案 1 :(得分:0)

尝试

var origObj = [{ "Id": "1", "name": "xxx", "age": "22" },
               { "Id": "1", "name": "yyy", "age": "15" },
               { "Id": "5", "name": "zzz", "age": "59" }], output;
               
output = [origObj.reduce((a,c) => (a[c.Id]=(a[c.Id]||[]).concat(c),a) ,{})];

console.log(output);