0

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?

1 Answer 1

2

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)

Sign up to request clarification or add additional context in comments.

3 Comments

I'm not sure since question is closed, this comment can show. with your advise, what if I have 3 values of array like : fruit = { apple: [2,2,2], orange:[3,3,3] }. this code will remain one empty object, @Spectric
@CODINNN I've updated my answer. It should work now. Sorry about that.
Thanks it works fine. you are so kind.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.