通过集团使用jQuery JSON数组 [英] Group by JSON array using jQuery

查看:163
本文介绍了通过集团使用jQuery JSON数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一组JSON数组和我想要的结果通过了ID列进行分组。我不会用underscore.js这一点,因为这不能在我们的项目中使用。唯一的选择就是用jQuery做。我的源阵列和预期结果如下。

VAR origObj = [{ID:1,名:XXX,年龄: 22},
               {ID:1,名:YYY,年龄:15},
               {ID:5,名:ZZZ,时代:59}]VAR输出= [{1:[{ID:1,名:XXX,时代:22},
                     {ID:1,名:YYY,年龄:15}],
               5:[{ID:5,名:ZZZ,时代:59}]}]


解决方案

您可以使用的 Array.prototype.reduce 来完成这件事。检查这个职位更多细节 http://stackoverflow.com/a/22962158/909535 扩展上,这就是你需要

  VAR数据= [{ID:1,名:XXX,时代:22},
    {ID:1,名:YYY,年龄:15},
    {ID:5,名:ZZZ,时代:59}];
    的console.log(data.reduce(功能(结果,电流){
        结果[current.Id] =结果[current.Id] || [];
        结果[current.Id] .push(电流);
        返回结果;
    },{}));

I have a set of JSON array and I want the result to be grouped by the "Id" column. I will not use underscore.js for this, as this can't be used in our project. The only option is to do it with jQuery. My source array and expected results are below.

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" }]}]

解决方案

You can use Array.prototype.reduce to get this done. Check this post for more details http://stackoverflow.com/a/22962158/909535 Extending on that this is what you would need

 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;
    }, {}));

这篇关于通过集团使用jQuery JSON数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆