skip to Main Content

"
[
{
"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"
}
] "

The above is the education

when I use JSON.stringify(education) I get the above, but can’t get to show with <p>{education[0]._id}</p>

it gives Uncaught TypeError: education[0] is undefined

I want to display this one by one like click on next then next element appears, I tried accessing the index element but was not able to.

3

Answers


  1. 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);
    
    Login or Signup to reply.
  2. This could happen when the data is not initially available.

    Try this

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

    or

    <p>{Array.isArray(education) && education.length > 0 ? education[0]._id || ''}</p>
    
    Login or Signup to reply.
  3. You can not access education data like education[0] after JSON.stringify(education),
    because JSON.stringify convert your education array object to JSON string.

    So after that converted, your education[0] value is "[" because it’s the string’s first character, that is why you got Uncaught TypeError: education[0]._id is undefined error.

    If you want to use that data in html element you have to use an array object without converting it to JSON.stringfy.

    For more clarification about JSON.stringyfy() visit this link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

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