如何访问JSON对象中的数组字段?

huangapple go评论85阅读模式
英文:

How to access the Array field in the Json Object?

问题

在你的组件中,你正在尝试访问 friendJson 对象中的 friends 数组并进行遍历,但遇到了一个错误,提示无法读取未定义的属性 map。这是因为 friendJson 对象是一个数组,而不是一个包含 friends 属性的对象。你需要先访问数组的元素,然后再遍历其中的 friends 属性。以下是修复错误的代码片段:

{
  // console.log(friendJson.friends)
  friendJson[0].friends.map((eachFriend) => {
    return <FriendItem key={eachFriend} friend={eachFriend}/>
  }) 
}

通过使用 friendJson[0],你访问了数组中的第一个对象,然后再遍历其 friends 属性。这应该会解决你遇到的错误。

英文:

So I have a Json object FriendJson and in it I have a array field friends.

Json Object:

[
  {
    &quot;id&quot;: 4,
    &quot;updated&quot;: &quot;2023-01-07T22:06:23.929206Z&quot;,
    &quot;created&quot;: &quot;2023-01-07T19:49:49.303182Z&quot;,
    &quot;user&quot;: 35,
    &quot;friends&quot;: [
      36,
      37,
      38,
      39
    ]
  }
]

The question is how to access friends array and traverse it. I am using react so I need to use map() for traversal. I am trying this in return part of a Functional component, so can use much functionalities of Javascript.

My component:

import React, {useContext, useEffect, useRef, useState} from &#39;react&#39;
import { useNavigate } from &#39;react-router-dom&#39;;
import AlertContext from &#39;../context/Alerts/AlertContext&#39;;
import FriendContext from &#39;../context/Friends/FriendContext&#39;;
import FriendItem from &#39;./FriendItem&#39;

export default function YourFriends() {

  const {friendJson, getFriends, addFriend, getUserId, getReceiverId} = useContext(FriendContext)
  const {showAlert} = useContext(AlertContext)

  const navigate = useNavigate()

  useEffect (() =&gt; {
    if(localStorage.getItem(&#39;authToken&#39;)) {
      getFriends()
    }
    else navigate(&#39;/signin&#39;)
  })



  return (
    &lt;&gt;
      &lt;div className=&quot;container&quot;&gt;
        &lt;h2 className=&quot;text-center&quot;&gt;Your Friends&lt;/h2&gt;
        {
          friendJson.length === 0 &amp;&amp; &lt;div className=&quot;text-conter&quot;&gt;You don&#39;t have any friends&lt;/div&gt;
        }
        {
          // console.log(friendJson.friends)
          friendJson.friends.map((eachFriend) =&gt; {
            return &lt;FriendItem key={eachFriend} friend={eachFriend}/&gt;
          }) 
        }
      &lt;/div&gt;
    &lt;/&gt;
  )
}

I tried in this way:

friendJson.friends.map((eachFriend) =&gt; {
     return &lt;FriendItem key={eachFriend} friend={eachFriend}/&gt;
})

But it throws error as:

TypeError: Cannot read properties of undefined (reading &#39;map&#39;)

And when I console.log(FriendJons.friends) the result is undefined.

答案1

得分: 2

如果你的 FriendJson 是一个数组,你应该通过以下方式访问朋友列表:

FriendJson[0].friends

而不是:

FriendJson.friends

潜在地,你可以迭代 FriendJson,并在其中的任何元素中获取 friends

friendJson.map((element) => {
  return element.friends.map((eachFriend) => {
     return <FriendItem key={eachFriend} friend={eachFriend}/>
  })
})

一般来说,处理像 "Cannot read properties of undefined (reading 'map')" 这样的错误的通用规则是打印具有你需要读取 "map" 的属性的对象,在你的情况下,如果这个解决方案不起作用,那么请检查 friendJson 是什么。

英文:

If your FriendJson is an array you should go to friends by

FriendJson[0].friends

rather than

FriendJson.friends

potentially you can iterate ofer FriendJson and in any of his elements get friends.

friendJson.map((element) =&gt; {
  return element.friends.map((eachFriend) =&gt; {
     return &lt;FriendItem key={eachFriend} friend={eachFriend}/&gt;
  })
})

general rule for errors like "Cannot read properties of undefined (reading 'map')"

is print object having property on which you need to read "map" in your case if this solution will not work then check what is friendJson.

huangapple
  • 本文由 发表于 2023年1月9日 18:03:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/75055664.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定