简体   繁体   中英

Accessing nested array in JSON response. Typescript-ReactJS

I have read some other questions with similar problem but I didn't figure out how to solve this. My code is writen a bit different and I don't know much Typescript, just started learning some months ago.

I built a backend where I expose an API. I can make a call to it and it returns:

{
    "content": [
        {
            "id": 1,
            "name": "Abantza",
            "origin": {
                "id": 2,
                "name": "Brazil"
            },
            "meaning": "",
            "gender": "FEMALE"
        },
        //more results....

I can render my table with the information of the first array (data as name, meaning, gender) but I can't print the origin.name info.

I have tried things like <td>{nameData.origin[0]}</td> {nameData.origin.map(x => (<td>{x.name}</td>))} without success.

My code in React is:

const Search = () => {

   const [nameResponse, setNameResponse] = useState<NameResponse>();

   useEffect(() => {
      const params = {
         page: 0,
         linesPerPage: 12
      }
      makeRequest({ url: '/names', params })
         .then(response => setNameResponse(response.data))
   }, [])

   return (
      <div className="search-container">
         <div className="search-result">
            <h3 className="search-result-title">Search results</h3>
            <table className="table table-striped table-hover table-sm" cellPadding="0" cellSpacing="0">
               <thead className="thead-dark">
                  <tr>
                     <th>NAME</th>
                     <th>MEANING</th>
                     <th>GENDER</th>
                     <th>ORIGIN</th>
                  </tr>
               </thead>
               <tbody>
                  {nameResponse?.content.map(nameData => (
                     <tr key={nameData.id}>
                        <td>{nameData.name}</td>
                        <td>{nameData.meaning}</td>
                        <td>{nameData.gender}</td>
                        <td>ORIGIN</td>             
                     </tr>
                  ))}
               </tbody>
            </table>
         </div>
      </div>
   )
}

console.log(nameResponse):

{content: Array(12), pageable: {…}, totalPages: 2, totalElements: 14, last: false, …}
content: Array(12)
0:
gender: "FEMALE"
id: 1
meaning: ""
name: "Abantza"
origin:
id: 2
name: "Brazil"
__proto__: Object
__proto__: Object
1: {id: 2, name: "Abarne", origin: {…}, meaning: "Ramos (es)", gender: "FEMALE"}
2: {id: 3, name: "Abauntza", origin: {…}, meaning: "", gender: "FEMALE"}

EDIT: add Name.ts :

export type NameResponse = {
   content: NameData[],
   totalPages: number
}

export type NameData = {
   id: number,
   name: string,
   meaning: string,
   gender: string,
   origin: Origin[]
}

export type Origin = {
   id: number,
   name: string
}

As pointed by @str, the problem was that my definition of origin was wrong. Once changed from origin: Origin[] (array) to origin: Origin (object) it worked.
Once again thanks @str!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM