I want return all objects inside nested loop
const data = [{ id:1, products:[{id:1, name:'apple'}, {id:2, name:'orange'}] },
{id:2, products:[{id:3, name:'grapes'}, {id:4, name:'banana'}, {id:5, name:'dragonFruit'}]
}]
let result = data.map(item=>{
item?.products?.map(row=> return row) })
console.log(result )
result should be:
[{id: 1, name: 'apple'}
{id: 2, name: 'orange'}
{id: 3, name: 'grapes'}
{id: 4, name: 'banana'}
{id: 5, name: 'dragonFruit'}
]
const data = [{ id:1, products:[{id:1, name:'apple'}, {id:2, name:'orange'}] },
{id:2, products:[{id:3, name:'grapes'}, {id:4, name:'banana'}, {id:5, name:'dragonFruit'}]
}]
let result = data.map(item=>{
let res = item.products.map((val) =>{
return val
})
return res
})
console.log(result)
check the above snippet, here inner map function return the value to the outer map and from the outer map function I'm returning the result
It is possible to use flatMap with map.
let result = data.flatMap(({products})=>
products.map(prd=> ({...prd })))
Let me show an example:
const data = [
{ id:1,
products:[
{id:1, name:'apple'},
{id:2, name:'orange'}
]
},
{id:2,
products:[
{id:3, name:'grapes'},
{id:4, name:'banana'},
{id:5, name:'dragonFruit'}
]
}
]
let result = data.flatMap(({products})=>
products.map(prd=> ({ ...prd })))
console.log(result)
You can use the flatMap. Read more about it at here
const data = [
{
id:1,
products:[{id:1, name:'apple'}, {id:2, name:'orange'}]
},
{
id:2,
products:[{id:3, name:'grapes'}, {id:4, name:'banana'}, {id:5, name:'dragonFruit'}]
}
];
const flatResult = data.flatMap(({products})=> products);
console.log(flatResult)
The above will return the output as
[
{
"id": 1,
"name": "apple"
},
{
"id": 2,
"name": "orange"
},
{
"id": 3,
"name": "grapes"
},
{
"id": 4,
"name": "banana"
},
{
"id": 5,
"name": "dragonFruit"
}
]