Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript split array values to object

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading