简体   繁体   中英

Group by Object ID's in Javascript

I have an array of ID's and organizations like so:

var ids = ['1','2', '3'];
var orgs =
    [ 
      { name: "Org 1", id: 1 },
      { name: "Org 2", id: 2 },
      { name: "Org 3", id: 2 }
    ]

I want to loop through these to output something like this:

{
    1: [
        {name: "Org 1", id: 1}
    ],
    2: [
        {name: "Org 2", id: 2},
        {name: "Org 3", id: 2}
    ]
}

I tried this without success:

var results = orgs.forEach(function (org) {
    if (results[org.id]) {
        results.push(org)
    } else {
        results[org.id] = [org]
    };
});

If you don't want to use a library like Underscore, Ramda, or Lo-Dash, then it's simple enough to write this using reduce :

var results = orgs.reduce(function(results, org) {
    (results[org.id] = results[org.id] || []).push(org);
    return results;
}, {})

you should use underscore and just return your id

http://underscorejs.org/#groupBy

_.groupBy([1.3, 2.1, 2.4], function(num){ return Math.floor(num); });
// => {1: [1.3], 2: [2.1, 2.4]}

you might also want to take a look at lo-dash

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM