[英]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: 我试图使用underscore.js或lodash获得的是一个哈希/对象,其中包含集合中所有值的数组:
{
id: [9, 11, 12],
name: ['Bob', 'Joe', 'Ash'],
age: [14, 15, 24]
}
Any thoughts? 有什么想法吗?
An answer in straightforward JavaScript code (no libraries): 简单的JavaScript代码(无库)的答案:
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. 这是一个替代的普通javascript答案。 It's basically the same as Nayuki's but possibly a bit more expressive.
它与Nayuki的基本相同,但可能更具表现力。
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. 我不太了解javascript。 But one approach would be to create three arrays, let's say
但是,一种方法是创建三个数组,比方说
var id = [];
var name = [];
var age = [];
Then loop through the people array 然后遍历people数组
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 现在您有三个具有各自ID,名称和年龄的数组
The last step would be to create your final object 最后一步是创建最终对象
var object = {
id:id
name:name
age:age
};
using array.map(): 使用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]
... 这个解决方案假设所有需要的密钥都可以在
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: 使用
Object.keys
, Array.prototype.reduce
和Array.prototype.map
方法的替代方法:
var res = Object.keys(people[0]).reduce(function(ret, key) {
ret[key] = people.map(function(el) { return el[key]; });
return ret;
}, {});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.