最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Group by JSON array using jQuery - Stack Overflow

programmeradmin3浏览0评论

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

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" }]}]
Share Improve this question edited Jul 8, 2019 at 7:08 Kamil Kiełczewski 92.5k34 gold badges395 silver badges370 bronze badges asked Jun 17, 2015 at 13:52 Deepak Ranjan JenaDeepak Ranjan Jena 4376 gold badges12 silver badges24 bronze badges 3
  • Can you show us the code that you have tried? – talemyn Commented Jun 17, 2015 at 14:02
  • I have tried with for loops, but that didn't work. That's why I am seeking help. – Deepak Ranjan Jena Commented Jun 17, 2015 at 14:03
  • I don't see any JSON here at all. These are javascript array/object literals. – Mike Brant Commented Jun 17, 2015 at 14:13
Add a ment  | 

2 Answers 2

Reset to default 12

You can use Array.prototype.reduce to get this done. Check this post for more details https://stackoverflow./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;
        }, {}));

Try

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);

发布评论

评论列表(0)

  1. 暂无评论