I am having an object in the below format where name
, age
and gender
are the column names and the object assigned to them are values of that column.
{
'name': {
0: 'Alpha',
1: 'Beta',
2: 'Gamma'
},
'age': {
0: 21,
1: 25,
2: 30
},
'gender': {
0: 'Male',
1: 'Female',
2: 'Male'
}
}
I want to convert above object into an array of objects.
Expected output :
[{
name: 'Alpha',
age: 21,
gender: 'Male'
}, {
name: 'Beta',
age: 25,
gender: 'Female'
}, {
name: 'Gamma',
age: 30,
gender: 'Male'
}]
What I tried so far ?
I tried with Object.keys()
to create the initial object with the keys first {name: '', age: '', gender: ''}
and then tried to iterate over the values of each key with the help of Object.values()
method to bind the each index values dynamically against each key of the object but not able to achieve.
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);
2
Answers
Since your nested values are indexed with sequential integers, you can use these keys to access the relevant index in the result array within a nested loop.
Here using nullish coallescing assignment (??=) to initialize each result object if it doesn’t already exist.
Or using the same logic in a
reduce()
call with a nestedforEach()
if you prefer.You can try array reduce