This is my data
export const courses = [
{
id: 0,
title: "first year",
subjects: [
{ id: 0, class: "french" },
{ id: 1, class: "history" },
{ id: 2, class: "geometry" }
],
},
{
id: 1,
title: "second year",
subjects: [
{ id: 0, class: "geography" },
{ id: 1, class: "chemistry" }
],
}
]
And this my code
export const studies = courses.map((course) => (
<div key={course.id}>
<h2>{course.title}</h2>
<li>
{course.subjects.class}
</li>
</div>
);
My aim is to list all classes per title. I tried adding a second key also in my list for the classes and the subjects per title, but no success. How to show all classes within the subjects per title?
2
Answers
To list all classes within the subjects per title, you need to iterate over the subjects array for each course. Here’s an updated version of your code that achieves this:
I also added another
.map()
function to iterate over the subjects array for each course. Inside this inner.map()
, we render a<li>
element for each subject, displaying the class property.Don’t forget to wrap the list
<li>
elements with a<ul>
element to create a valid HTML list structure.With these changes, your code should now list all classes within the subjects per title correctly.
To show all classes per title, you need to iterate over the
subjects
array within eachcourse
object. I have modified you code below;In the modified code above, the
map
function is used to iterate over the courses array. Thetitle
is displayed inh2
heading and for eachcourse
, we iterate through the subjects array and list the class using theul
andli
elements. Hope this helps!