简体   繁体   English

在反应中返回嵌套循环内的所有对象

[英]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 .可以将flatMapmap一起使用。

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 .您可以使用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 .您可以使用嵌套循环来执行此操作,首先map data ,然后映射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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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