5

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?

1
  • It's possible to do this manually without underscore.js. Would you accept such an answer? Commented Oct 8, 2015 at 20:26

5 Answers 5

7

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]);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

2

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

Comments

2

using array.map():

var acc = {};
for (k in people[0]) {
    acc[k] = people.map(function (x) {
        return x[k]
    })
}

fiddle

this solution assumes that all the needed keys will be found in people[0] ...


EDIT:

this is a more extreme version that should catch the keys along the way:

 people.reduce(function (ac, item) {
    for (k in item) {
        if(!ac[k])
        ac[k] =[];
        ac[k].push(item[k])
        }
    return ac
}, {})

fiddle2

Comments

1

An alternative that uses Object.keys, Array.prototype.reduce and Array.prototype.map methods:

var res = Object.keys(people[0]).reduce(function(ret, key) {
     ret[key] = people.map(function(el) { return el[key]; });
     return ret;
}, {});

Comments

1

I don't know javascript much. But one approach would be to create three arrays, let's say

var id = [];
var name = [];
var age = [];

Then loop through the people array

for(var i=0; i<people.length; i++){
  id.push(people[i].id);
  name.push(people[i].name);
  age.push(people[i].age);
}

Now you have three arrays with respective ids, names and ages

The last step would be to create your final object

var object = {
  id:id
  name:name
  age:age
};

2 Comments

This actually might be the most efficient answer in terms of time complexity. Instead of the nested loops all other answers suggest, this only loops through once.
yes, since it loops only once, it's time complexity will be O(n).

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.