-1

I have to access data from an API that is similar to:

{
 "speakers": [
   {
     "name": "speakerName",
     "profile_picture": "profilePic"
   }
 ]
},
{
 "speakers": []
}

I saved speakers as an array, but I am not sure how to access the objects inside the inner array. The speakers parameter gives the entire array (name and profile picture).

const PublicEventsInfo = ({speakers}) => { 
 
}

When I try the code below, I get the error: TypeError: Cannot read properties of undefined.

speakers[0].name

How would I access just the name portion of speakers inside PublicEventsInfo?

frizefries
  • 29
  • 5

3 Answers3

1

Either obj.key or obj[key]. However, as you have an array you need to access it with a numerical index. So assuming you want the first in the array and there is always one in the array, you could do like this:

const test = {
 "speakers": [
   {
     "name": "speakerName",
     "profile_picture": "profilePic"
   }
 ]
}
const PublicEventsInfo = ({speakers}) => { 
 console.log(speakers[0].name)
}
PublicEventsInfo(test)

However, it looks like the data you provided has the incorrect structure:

{
 "speakers": [
   {
     "name": "speakerName",
     "profile_picture": "profilePic"
   }
 ]
},
{
 "speakers": []
}

This is not a valid json, unless wrapped in an array.

ᴓᴓᴓ
  • 1,178
  • 1
  • 7
  • 18
  • The Json is wrapped in an array. When I try to do console.log(speakers[0].name), I get an error of TypeError: Cannot read properties of undefined (reading 'name'). – frizefries Feb 24 '22 at 01:15
0

If I understand this question correctly

You should just be able to do const name = speakers.name

StarnightFox
  • 204
  • 1
  • 6
0

I think you mean something like this? data.map(x=>x.speakers).flat() can do someting like unwrap speakers and concat

let data = [{
    "speakers": [{
      "name": "speakerName",
      "profile_picture": "profilePic"
    }]
  },
  {
    "speakers": []
  }
]

const PublicEventsInfo = ({
  speakers
}) => {
  return <ul>{speakers.map((x,i)=><li key={i}>{x.name}:{x.profile_picture}</li>)}</ul>
}

export const Page=()=><PublicEventsInfo speakers={data.map(x=>x.speakers).flat()}>
Josh Lin
  • 2,397
  • 11
  • 21