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;
}
Working jsFiddle: http://jsfiddle.net/jfriend00/0jjquju9/
Explanation:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With