Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Trying to select property from array within object, within array. Thrown TypeError: Cannot read properties of undefined

I am trying to make a project with React that can display course homework on a to-do list. I currently have some test data, shown here:

 const courses = [
    {
      courseName: "Fundies 2",
      classCode: "CS2510",
      startTime: "4:35 PM",
      location: "236 Richards Hall",
      color: "red",
      homework: [{ hwName: "HW3", timeDue: "8:30 PM" }]
    },
    {
      courseName: "Mathematical Reasoning",
      classCode: "MATH1365",
      startTime: "10:20 AM",
      location: "235 Ryder Hall",
      color: "blue",
      homework: [
        { hwName: "HW2", timeDue: "midnight" },
        { hwName: "HW3", timeDue: "midnight" },
      ]
    },
  ];

I made a function to create a component out of this data, shown below.

const formattedCourses = courses.map((course) => {
    return (
      <Task
        key={course.homework[1].hwName}
        timeDue={course.homework[1].timeDue}
        courseName={course.courseName}
        hwName={course.homework[1].hwName}
        color={course.color}
      />
    );
  });

I want the component to be made with the first entry in the homework array. However, whenever I try to compile, I get

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

"TypeError: Cannot read properties of undefined (reading ‘hwName’)"

How can I fix this?

Any and all help is greatly appreciated!

>Solution :

You index is incorrect. If you want the first entry then it should be 0 instead of 1

const formattedCourses = courses.map((course) => {
    return (
      <Task
        key={course.homework[0].hwName}
        timeDue={course.homework[0].timeDue}
        courseName={course.courseName}
        hwName={course.homework[0].hwName}
        color={course.color}
      />
    );
  });
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading