My data is organized in an object with column names such as name
, age
, and gender
, each assigned values for those columns.
{
'name': {
0: 'Alpha',
1: 'Beta',
2: 'Gamma'
},
'age': {
0: 21,
1: 25,
2: 30
},
'gender': {
0: 'Male',
1: 'Female',
2: 'Male'
}
}
I am looking to convert the above object into an array of objects.
Desired output :
[{
name: 'Alpha',
age: 21,
gender: 'Male'
}, {
name: 'Beta',
age: 25,
gender: 'Female'
}, {
name: 'Gamma',
age: 30,
gender: 'Male'
}]
My approach so far ?
I attempted using Object.keys()
to create an initial object with keys as {name: '', age: '', gender: ''}
. Then, I tried to loop through the values of each key using Object.values()
to bind the values dynamically against each key, but encountered difficulties in achieving this task.
const obj = {
'name': {
0: 'Alpha',
1: 'Beta',
2: 'Gamma'
},
'age': {
0: 21,
1: 25,
2: 30
},
'gender': {
0: 'Male',
1: 'Female',
2: 'Male'
}
};
const columnNameObj = {}
const arr = []
Object.keys(obj).forEach(column => {
Object.values(obj[column]).forEach((item, index) => {
columnNameObj[column] = obj[column][index] // <-- Here I am doing a mistake as it iterates the whole loop and the last value get assigned to the object property. Object should be pushed on each iteration instead of ending the inner loop but somehow I am stuck here.
})
arr.push(columnNameObj);
})
console.log(arr);