简体   繁体   中英

How to map nested array containing objects in react js?

Im not really sure if the question is right but here is the problem:

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

]

The exercise here is to render this array, but it has to be in a way that more courses can be added later and from components. Here are my components that im trying to make:

     const Content = (props) => {
 return(
  props.parts.map(part => {
    console.log(part.parts,'part', part.id)
  })
  )
}



const Part = (props) =>{
 console.log(props)
  return <div>
    {props.part.name}
  </div>}

I have the data i want in the map, but I just dont get how to make the indexes dynamic... Like in the map it would go through all of the arrays sub-parts and give the names and exercises

Like I mentioned in the comments, it sounds like what you are missing is the dynamic rendering of components based on an array of data. The primary issue is you need to update the Content component to actually render a Part for every item in the parts array. That would look something like this

const Content = ({parts}) => {
  return (
    <>
      { parts.map(part => <Part key={part.id} part={part) />) }
    </>
  )
}

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