Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I combine an array of objects with the same keys into one object?

If I start with the following:

var people = [
   {id: 9, name: 'Bob', age: 14},
   {id: 11, name: 'Joe', age: 15},
   {id: 12, name: 'Ash', age: 24}]

What I am trying to get using underscore.js or lodash is a single hash/object with an array of all the values from the collection:

{
   id: [9, 11, 12],
   name: ['Bob', 'Joe', 'Ash'],
   age: [14, 15, 24]
}

Any thoughts?

like image 338
user225088 Avatar asked Oct 08 '15 20:10

user225088


2 Answers

An answer in straightforward JavaScript code (no libraries):

var result = {};
for (var i = 0; i < people.length; i++) {
    var item = people[i];
    for (var key in item) {
        if (!(key in result))
            result[key] = [];
        result[key].push(item[key]);
    }
}
like image 138
Nayuki Avatar answered Oct 04 '22 19:10

Nayuki


Here's an alternate plain javascript answer. It's basically the same as Nayuki's but possibly a bit more expressive.

var obj = {};
people.forEach(function(person){
    for(prop in person) {
        obj[prop] = obj[prop] || [];
        obj[prop].push(person[prop]);
    }
});
like image 28
Matt O'Connell Avatar answered Oct 04 '22 19:10

Matt O'Connell