javascriptnode.jsreactjs

Uncaught TypeError: education[0] is undefined


[
  {
    "eduTitle": "test",
    "eduDescription": "test",
    "eduStartDate": "03/24/23",
    "eduEndDate": "03/24/23",
    "_id": "641c0110cb3a9b14cf0e3030"
  },
  {
    "eduTitle": "test",
    "eduDescription": "test",
    "eduStartDate": "03/24/23",
    "eduEndDate": "03/24/23",
    "_id": "641c0110cb3a9b14cf0e3031"
  }
]

When I use JSON.stringify(education), I get the above output. However, I can’t access and display a specific value like

<p>{education[0]._id}</p>

it gives me the error:

Uncaught TypeError: education[0] is undefined.

I want to display each item one by one, for example by clicking a “Next” button to show the next element. I tried accessing elements by index but couldn’t get it to work.


Solution

  • You already have stringified JSON. In order to access it, you should do the reverse: instead of JSON.stringify(education), you should do JSON.parse(education).

    Once you parse the array, you can access its elements.

    const education = JSON.parse(data);
    
    console.log(education[0]?._id);