'Can't print a dict: Uncaught TypeError: Cannot read properties of undefined

I've this error:

crew.js:6 Uncaught TypeError: Cannot read properties of undefined (reading 'first')

From an API (I'm using FastAPI for backend) I've this return:

{"id":"1","name":{"first":"Sponge","last":"Bob"},"role":"Captain","active":true}

While printing on screen through REACT with a code like this

const allcrew = crewList.map((index)=>
    <li key={index.id}>{index.name.first} {index.name.last} <br /> <i>{index.role}</i></li>
);

it looks like "first" is undefined while it is in my model.py file

from pydantic import BaseModel

class CrewName(BaseModel):
  first: str
  last: str

class Crew(BaseModel):
id: str
name: list [CrewName] = []
role: str
active: bool

someone can understand the issue? Before use the var "name" as a dict but just like a str all was working fine.

Thanks!



Solution 1:[1]

You use the map function when it is inappropriate for the situation. Indeed, the map() method creates a new array with the results of the call of a given function on EACH element of the calling array. Now, you use all the results of crewList directly, not one by one.

Using map as you do, on the first pass through map, index matches "id": "1" so it doesn't know name.first since it is undefined. map processes each element separately.

So you can directly access the elements without using the map method.

const allcrew = <li key={crewList.id}>{crewList.name.first} {crewList.name.last} <br /> <i>{crewList.role}</i></li>
);

However, if later you want to create several li elements, at this point you can use the map method with an array of crew on which you want to iterate. For example :

const crewList = [
    {"id":"1","name":"first":"Sponge","last":"Bob"},"role":"Captain","active":true},
    {"id":"2","name":"first":"Iron","last":"Man"},"role":"Superhero","active":true}
]

const allcrew = crewList.map((index)=>
    <li key={index.id}>{index.name.first} {index.name.last} <br /> <i>{index.role}</i></li>
);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 fchancel