[英]How can I convert an array of objects into single object while keys of all the objects are same and value may differ
[英]How can I combine an array of objects with the same keys into one object?
如果我從以下開始:
var people = [
{id: 9, name: 'Bob', age: 14},
{id: 11, name: 'Joe', age: 15},
{id: 12, name: 'Ash', age: 24}]
我試圖使用underscore.js或lodash獲得的是一個哈希/對象,其中包含集合中所有值的數組:
{
id: [9, 11, 12],
name: ['Bob', 'Joe', 'Ash'],
age: [14, 15, 24]
}
有什么想法嗎?
簡單的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]);
}
}
這是一個替代的普通javascript答案。 它與Nayuki的基本相同,但可能更具表現力。
var obj = {};
people.forEach(function(person){
for(prop in person) {
obj[prop] = obj[prop] || [];
obj[prop].push(person[prop]);
}
});
我不太了解javascript。 但是,一種方法是創建三個數組,比方說
var id = [];
var name = [];
var age = [];
然后遍歷people數組
for(var i=0; i<people.length; i++){
id.push(people[i].id);
name.push(people[i].name);
age.push(people[i].age);
}
現在您有三個具有各自ID,名稱和年齡的數組
最后一步是創建最終對象
var object = {
id:id
name:name
age:age
};
使用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.