简体   繁体   中英

Return all objects inside nested loop in react

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"
  }
]

You can do it using a nested loop, first map over the data and then over the products .

 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" }, ], }, ]; function App() { return ( <ul> {data.map(({ products }) => products.map((p) => <li key={p.id}>{p.name}</li>) )} </ul> ); } const root = ReactDOM.createRoot(document.getElementById("root")); root.render(<App />);
 <script crossorigin src="https://unpkg.com/react@18/umd/react.development.js"></script> <script crossorigin src="https://unpkg.com/react-dom@18/umd/react-dom.development.js"></script> <div id="root"></div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM