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?
CodePudding user response:
you can nest loops.
{course.map((item)=>
{
items.parts.map((p)=><Part key={p.id} part={p.name} exercise=
{p.exercises}/> )
}
)}
CodePudding user response:
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>
)
}
CodePudding user response:
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>