简体   繁体   English

如何将具有相同键的对象数组合到一个对象中?

[英]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]
    })
}

fiddle 小提琴

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
}, {})

fiddle2 fiddle2

An alternative that uses Object.keys , Array.prototype.reduce and Array.prototype.map methods: 使用Object.keysArray.prototype.reduceArray.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.

相关问题 如何在所有对象的键相同且值可能不同的情况下将对象数组转换为单个 object - How can I convert an array of objects into single object while keys of all the objects are same and value may differ 我有一组对象,如果其中一个键匹配(不覆盖初始属性),我想将它们组合成一个 object - I have an array of objects and want to combine them into one object IF the one of the keys match (without overwriting the initial properties) 将两个 Javascript 对象合并为一个具有相同键的对象 - Combine two Javascript Objects into one Object with same keys 如何将一组对象组合到另一个对象数组中,同时还组合了公共键 - How can i combine an array of objects into another array of objects while also combining the common keys 检查还包含嵌套的 arrays 和对象的对象数组是否相同,如果是,则将它们合并为一个 object 并将键添加到一起 - Check if array of objects, which also contain nested arrays with objects, are the same, if so, combine them into one object and add the keys together 如何在数组中找到具有相同键值的对象? - How can I find objects with same keys values in array? 将一组对象组合成一个 OBJECT - Combine an array of objects into one OBJECT 如何将对象数组转换为具有相同值但具有修改键的对象数组? - How can I convert an array of objects into an array of objects with the same values but with modified keys? 我需要将我的对象数组转换为具有特定键的 object - I need to convert my array of objects into one object with specific keys 如何将这些数据合并到一个对象中? - How can I combine this data into one Object?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM