How to access the Array field in the Json Object?

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

Json Object:

    "id": 4,
    "updated": "2023-01-07T22:06:23.929206Z",
    "created": "2023-01-07T19:49:49.303182Z",
    "user": 35,
    "friends": [

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 'react'
import { useNavigate } from 'react-router-dom';
import AlertContext from '../context/Alerts/AlertContext';
import FriendContext from '../context/Friends/FriendContext';
import FriendItem from './FriendItem'

export default function YourFriends() {

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

  const navigate = useNavigate()

  useEffect (() => {
    if(localStorage.getItem('authToken')) {
    else navigate('/signin')

  return (
      <div className="container">
        <h2 className="text-center">Your Friends</h2>
          friendJson.length === 0 && <div className="text-conter">You don't have any friends</div>
          // console.log(friendJson.friends)
 => {
            return <FriendItem key={eachFriend} friend={eachFriend}/>

I tried in this way: => {
     return <FriendItem key={eachFriend} friend={eachFriend}/>

But it throws error as:

TypeError: Cannot read properties of undefined (reading 'map')

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

>Solution :

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


rather than


potentially you can iterate ofer FriendJson and in any of his elements get friends. => {
  return => {
     return <FriendItem key={eachFriend} friend={eachFriend}/>

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.

Leave a Reply