简体   繁体   中英

How to map through an array of values of a single prop in an array of objects in React?

I was earlier using map() to loop through values of a single prop within an object.

const Content = (p)=>{
  console.log(p)
  const {parts} =p
  
  return (    
    <div>
      {parts.map((item)=> 
        <Part key={item.id} part={item.name} exercise={item.exercises}/>  
      )}
      
    </div>    
  )
}

Now the object is expanded to an array of objects, how will I loop through my values still?

const course = [
    {
      name:'Half Stack application development',
      id:1,
      parts: [
        {
          name:'Fundamentals of React',
          exercises: 10,
          id: 1
        },
        {
          name:'Using props to pass data',
          exercises:7,
          id: 2
        },
        {
          name:'State of a component',
          exercises:14,
          id: 3
        }
    ]
  },
  {
    name: 'Node.js',
    id: 2,
    parts: [
      {
        name: 'Routing',
        exercises: 3,
        id: 1
      },
      {
        name: 'Middlewares',
        exercises: 7,
        id: 2
      }
    ]
  }
]

Am I supposed to use a map inside of a map, if yes then how should I implement it?

you can nest loops.

{course.map((item)=> 
        {
           items.parts.map((p)=><Part key={p.id} part={p.name} exercise= 
           {p.exercises}/> )
}  
      )}

There are many approaches, one being:

Simply create an array of JSX elements, before your return statement. Render that array directly. Here is a simple exmaple with a p tag. You can use your own component:

import "./styles.css";

export default function App() {
  const course = [
    {
      name:'Half Stack application development',
      id:1,
      parts: [
        {
          name:'Fundamentals of React',
          exercises: 10,
          id: 1
        },
        {
          name:'Using props to pass data',
          exercises:7,
          id: 2
        },
        {
          name:'State of a component',
          exercises:14,
          id: 3
        }
    ]
  },
  {
    name: 'Node.js',
    id: 2,
    parts: [
      {
        name: 'Routing',
        exercises: 3,
        id: 1
      },
      {
        name: 'Middlewares',
        exercises: 7,
        id: 2
      }
    ]
  }
];

let comp = [];
course.forEach((p) => {
  comp = [comp, ...(p.parts).map((item)=> 
  <p key={item.id}>{item.name}</p>
)];
});
return (    
  <div>
    {comp}
    
  </div>    
)
}

Sandbox

A short approach is to use flatMap in conjunction with map:

<div>
{
    course.flatMap(el1 => el1.parts.map(el2 =>
        <Part key={el2.id} part={el2.name} exercise={el2.exercises} />
    )
}
</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