I’m trying to convert an object where the property values are arrays to an array of objects where each object has the same properties as the original, but the values are from the arrays.
For example, given the following array:
fruit = [{
"apple": [2, 3],
"orange": [2, 3]
}]
I would like:
fruit = [{
"apple": 2,
"orange": 2
},
{
"apple": 3,
"orange": 3
}
]
How should I accomplish this with JavaScript?
>Solution :
It’s more logical for fruit to be an object rather than an array with only one item. In that case, you can loop through the number of properties (keeping track of the index), and use a nested loop to loop through each property value and extract the item at the outer loop index.
fruit = {
"apple": [2, 3],
"orange": [2, 3]
}
const res = Object.values(fruit)[0].reduce((a,b,i) => {
a.push(Object.fromEntries(Object.keys(fruit).map(e => [e, fruit[e][i]])))
return a;
}, [])
console.log(res)