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]);
}
}
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]);
}
});
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
};
using array.map():
var acc = {};
for (k in people[0]) {
acc[k] = people.map(function (x) {
return x[k]
})
}
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
}, {})
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;
}, {});
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.