skip to Main Content

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


  1. 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:

    export const studies = courses.map((course) => (
      <div key={course.id}>
        <h2>{course.title}</h2>
        <ul>
          {course.subjects.map((subject) => (
            <li key={subject.id}>{subject.class}</li>
          ))}
        </ul>
      </div>
    ));
    

    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.

    Login or Signup to reply.
  2. To show all classes per title, you need to iterate over the subjects array within each course object. I have modified you code below;

    export const studies = courses.map(({ id, title, subjects }) => (
      <div key={id}>
        <h2>{title}</h2>
        <ul>
          {subjects.map((subject) => (
            <li key={subject.id}>{subject.class}</li>
          ))}
        </ul>
      </div>
    ))
    

    In the modified code above, the map function is used to iterate over the courses array. The title is displayed in h2 heading and for each course, we iterate through the subjects array and list the class using the ul and li elements. Hope this helps!

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search