Reputation: 418
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;
})
})
Upvotes: 1
Views: 72
Reputation: 36574
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)
Upvotes: 4