2

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" }]}]
3
  • Can you show us the code that you have tried? 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. Commented Jun 17, 2015 at 14:03
  • I don't see any JSON here at all. These are javascript array/object literals. Commented Jun 17, 2015 at 14:13

2 Answers 2

12

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

Sign up to request clarification or add additional context in comments.

4 Comments

Hey!! Cool man. That worked. I just assigned that to a variable instead of printing on console.
This seems to work great!. Is it compatible across all web browsers?
seems like it is.. in the latest browsers.. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
Its Cool, But how can I apply with multiple key group by?
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.