Roy Arturo Roy Arturo - 1 year ago 59
Javascript Question

create array of values with same key from an array of objects

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.


Answer Source

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
    return output;

Working jsFiddle:


  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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download