Skip to content
Advertisement

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?

Advertisement

Answer

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

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement