1

I have the following Array of Objects. I want to generate as many Objects based on inner 'Y' array length.

var arr = [{x:1,y:[1,2]},{x:2,y:[1,2]}];

Expected Output as follows

var arr = [{x:1,y:1},{x:1,y:2},{x:2,y:1},{x:2,y:2}]

Code I have tried but i could't

arr.forEach(item => {
  return item.y.forEach(inner => {
    return inner;
  })
})

1 Answer 1

4

You can use flatMap() with nested map(). Use flatMap() on the main array and inside that use map() on y property of that object. return an object from inner map() function whose y property will be different and x will be the same

var arr = [{x:1,y:[1,2]},{x:2,y:[1,2]}];
const res = arr.flatMap(({x, y}) => y.map(y => ({x, y})));
console.log(res)

If you don't understand the flatMap below is the version using nested forEach

var arr = [{x:1,y:[1,2]},{x:2,y:[1,2]}];
const res = [];
arr.forEach(a => {
  a.y.forEach(y => {
    res.push({x: a.x, y});
  })
})
console.log(res)

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

Comments

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.