Deepak Ranjan Jena
Deepak Ranjan Jena

Reputation: 437

Group by JSON array using jQuery

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

Upvotes: 2

Views: 17614

Answers (2)

Kamil Kiełczewski
Kamil Kiełczewski

Reputation: 92477

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

Upvotes: 0

meteor
meteor

Reputation: 2568

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

Upvotes: 12

Related Questions