I have following input data:
{
'a': [1, 2, 3],
'b': ['x', 'y', 'z'],
'c': ['a', 'b', 'c'],
}
I am trying to change above input data into following data structure:
{
'0': { a: 1, b: 'x', c: 'a' },
'1': { a: 2, b: 'y', c: 'b' },
'2': { a: 3, b: 'z', c: 'c' }
}
My Javascript Code is:
let parentDataset = {
'a': [1, 2, 3],
'b': ['x', 'y', 'z'],
'c': ['a', 'b', 'c'],
}
let children = {};
let parent = {};
for (let key in parentDataset) {
let i = 0;
for (let value of parentDataset[key]) {
children[key] = value;
parent[i] = children;
i++;
}
}
console.log('parent', parent);
But I am getting following output where last value is over writing previous two values as below:
{
'0': { a: 3, b: 'z', c: 'c' },
'1': { a: 3, b: 'z', c: 'c' },
'2': { a: 3, b: 'z', c: 'c' }
}
Any solution and explanation would be much appreciated!
After getting the list of keys, you can Array#reduce one of the arrays to a series of objects, and populate them using Array#forEach and Object#assign:
const obj = {
'a': [1, 2, 3],
'b': ['x', 'y', 'z'],
'c': ['a', 'b', 'c'],
};
const keys = Object.keys(obj);
const result = obj[keys[0]].reduce((r, _, i) => {
const o = r[i] = {};
keys.forEach((key) => Object.assign(o, { [key]: obj[key][i] }));
return r;
}, {});
console.log(result);
And here is a working version of your code:
const parentDataset = {
'a': [1, 2, 3],
'b': ['x', 'y', 'z'],
'c': ['a', 'b', 'c'],
}
const parent = {};
for (const key in parentDataset) {
let i = 0;
for (const value of parentDataset[key]) {
!parent[i] && (parent[i] = {}); // create a new object if one is needed
parent[i][key] = value; // add the key and value to the object
i++;
}
}
console.log('parent', parent);
Another solution would be to reduce object's values. For example:
const data = {
'a': [1, 2, 3],
'b': ['x', 'y', 'z'],
'c': ['a', 'b', 'c'],
}
const result = Object.values(data).reduce((acc, subarr, idx, arr) => {
return { ...acc, [idx]: arr.map(sub => sub[idx]) }
}, {})
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