Group by JSON array using jQuery

17.3k Views Asked by At

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

There are 2 best solutions below

4
On BEST ANSWER

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

0
On

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