Home > other >  How to access deeply nested array in Javascript
How to access deeply nested array in Javascript

Time:02-17

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

{
 "name": "nameofevent",
 "speakers": [
   {
     "name": "speakerName"
   }
 ]
}

I am not sure how to access the speakerName inside speakers. Below is what I have, but I don't think I can do it that way because the speaker name has the same variable name as name. How would I access the speakerName?

{publicEvents.map((event) => {
    const { name, speakers: [{name}]} = event;
    return (
        <EventsCard
            eventName={name}
            speakerName={name}
        />
    ); 
})}

CodePudding user response:

You can assign different variable names when destructuring.

{publicEvents.map((event) => {
    const { name: eventName, speakers: [{name: speakerName}]} = event;
    return (
           <EventsCard
                 eventName={eventName}
                 speakerName={speakerName}
           />
      ); 
    })}

CodePudding user response:

As James said, it is an array so you need to specify that item in the array, since it is possible to have multiple speakers. Something like this could be used to select the first item:

speakers[0].name
  • Related