How can I combine a set of objects with the same keys into a single object?

advertisements

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?


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