-1

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": [
      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 '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')) {
      getFriends()
    }
    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)
          friendJson.friends.map((eachFriend) => {
            return <FriendItem key={eachFriend} friend={eachFriend}/>
          }) 
        }
      </div>
    </>
  )
}

I tried in this way:

friendJson.friends.map((eachFriend) => {
     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.

Love S
  • 1
  • 3
  • Try to access the friends list like this: `FriendJson[0].friends` Your FriendJson is an array of objects, in this case 1 object, then you have the friends property. – Juljo Shahini Jan 09 '23 at 10:06
  • From the given JSON, it looks like `friendJson` is, itself, an array, so you will have to either loop through it or get its first element, in order to get access to the inner `friends` array. – Haroldo_OK Jan 09 '23 at 10:08
  • @Haroldo_OK Yeah but I cannot use loop right there, that's the problem – Love S Jan 09 '23 at 10:09
  • @JuljoShahini not working.. – Love S Jan 09 '23 at 10:09
  • 1
    [There's no such thing as a "JSON Object"](http://benalman.com/news/2010/03/theres-no-such-thing-as-a-json/) – Andreas Jan 09 '23 at 10:10
  • @LoveS that was one of the issues I noticed, also check this: `https://codesandbox.io/s/gifted-panka-iu58q9?file=/src/App.js` – Juljo Shahini Jan 09 '23 at 10:15

1 Answers1

2

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) => {
  return element.friends.map((eachFriend) => {
     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.

Daniel
  • 7,684
  • 7
  • 52
  • 76
  • Thank you it worked, but I didn't get the intuition though – Love S Jan 09 '23 at 10:21
  • ```FriendJson[0].friends.map((eachFriend) => {... })``` Why is this not working and giving ```TypeError: Cannot read properties of undefined (reading 'friends')```?? – Love S Jan 09 '23 at 10:32
  • @LoveS It's because `FriendJson` is an array; the `FriendJson` array does not contain an attribute `friends`; the object inside that outermost array is that has those attributes. So, you need to either get the first element of the outermost array, or loop through the outermost array, in order to get the said object. – Haroldo_OK Jan 09 '23 at 10:34
  • Then how to directly access the ```object inside that outermost array```? How to do it in my example without outer ```map()``` in your answer? Is there any other way, just want to know because I want to learn – Love S Jan 09 '23 at 10:38
  • There does not seem to be much alternative here: it would either be necessary to use the first element of the array, or use some form of looping/iterating the outer array, `map()` being the most fitting for that in this case. – Haroldo_OK Jan 09 '23 at 13:19