使用对象数组中的相同键创建值数组 [英] create array of values with same key from an array of objects

查看:137
本文介绍了使用对象数组中的相同键创建值数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下所示的对象数组:

I have an array of objects that looks like this:

[
     {
      key1: val_1.a
      key2: val_2.a
      key3: val_3.a
     },{
      key1: val_1.b
      key2: val_2.b
      key3: val_3.b
     },{
      key1: val_1.c
      key2: val_2.c
      key3: val_3.c
     }
]

我想使用该对象创建另一个看起来像这样的对象:

I want to use that object to create another object that looks like this:

{ 
    key1: [val_1.a, val_1.b, val_1.c]
    key2: [val_2.a, val_2.b, val_2.c]
    key3: [[val_3.a, val_3.b, val_3.c]
}

由于每个对象中的键都相同,我只想在数组中保存与每个键对应的所有值。

Since the keys are the same in each object I just want to save in an array all the values that correspond to each key.

请,如果有人之前必须这样做并且可以共享代码,那就太好了。在此先感谢。

Please, If there is anyone who have had to do this before and could share the code it would be great. Thanks in advance.

推荐答案

你可以这样做,以适用于所有浏览器,甚至可以工作对象没有完全相同的键集(例如,它只会累积存在的任何键的数据):

You can do it like this in a way that will work in all browsers and will even work if all objects don't have the exact same set of keys (e.g. it will just accumulate data for whatever keys exist):

function combineKeyData(data) {
    var output = {}, item;
    // iterate the outer array to look at each item in that array
    for (var i = 0; i < data.length; i++) {
        item = data[i];
        // iterate each key on the object
        for (var prop in item) {
            if (item.hasOwnProperty(prop)) {
                // if this keys doesn't exist in the output object, add it
                if (!(prop in output)) {
                    output[prop] = [];
                }
                // add data onto the end of the key's array
                output[prop].push(item[prop]);
            }
        }
    }
    return output;
}

工作jsFiddle: http://jsfiddle.net/jfriend00/0jjquju9/

Working jsFiddle: http://jsfiddle.net/jfriend00/0jjquju9/

说明:


  1. 对于数组中的每个项目

  2. 对于数组中项目中的每个键

  3. 将键作为空数组添加到输出对象(如果它尚不存在)

  4. 将数据添加到输出对象中该键的数组末尾

  5. 返回生成的新对象

  1. For each item in the array
  2. For each key in an item in the array
  3. Add the key as an empty array to the output object if it doesn't already exist
  4. Add the data onto the end of the array for that key in the output object
  5. Return the resulting new object

这篇关于使用对象数组中的相同键创建值数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆