0

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 can I show all classes within the subjects per title?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Boq7
  • 71
  • 7

1 Answers1

1

To list all classes within the subjects as per the 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.

DavidW
  • 29,336
  • 6
  • 55
  • 86
ichang3765
  • 45
  • 8
  • Ok. Do you have any suggestions for making my posts less wordy? I normally type formally. – ichang3765 Jul 15 '23 at 16:50
  • On a closer look I'm actually less convinced, so I'll remove my comments. Sorry if they were unfair. You used a few of ChatGPT's favourite phrases, but the rest looks legitimate, if a little formal – DavidW Jul 15 '23 at 17:30
  • Thank you. Do you know if you can follow in Stack Overflow? I'm rather new. – ichang3765 Jul 15 '23 at 17:42
  • You can't follow a person. You can follow a question or answer to be told when there's updates (there's a button below the post). You can follow a tag (the button is called "watch tag") to see questions on a topic – DavidW Jul 15 '23 at 17:45