Here is a dataset that needs reformatting
let data = [
{
apple:1,
banana:2,
cherry:3
},
{
apple:4,
banana:5,
cherry:6
},
{
apple:7,
banana:8,
cherry:9
}
]
The desired format for the data is as follows:
{
apple: [1,4,7],
banana: [2,5,8],
cherry: [3,6,9]
}
Below is a proposed solution:
let data = [
{
apple:1,
banana:2,
cherry:3
},
{
apple:4,
banana:5,
cherry:6
},
{
apple:7,
banana:8,
cherry:9
}
]
function reformatData (data) {
console.log(typeof data) // WHY IS THIS RETURNING AN OBJECT???
let keys = Object.keys(data[0])
const resultObj = {}
for (let key of keys) {
resultObj[key] = []
}
data.forEach((x,idx)=> {
for (let key in x) {
resultObj[key].push(x[key])
}
})
return resultObj
}
reformatData(data)
Although this code works, it may not be the most efficient. I am struggling with understanding the following concepts:
- Initially,
data
appears to me as an array with one index containing three objects. For instance,data[0] = {obj1},{obj2},{obj3}
, but when I check its type usingtypeof
, it shows as an object. - When I log
data
at a specific index likedata[1]
, it displays{apple:4,banana:5,cherry:6}
resembling an array. - I am confused about what kind of data structure this is and what is happening here?
Please provide a more efficient solution and clarify these concepts for me.