Search code examples
javascriptarraysdestructuring

How to access deeply nested array in Javascript


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}
        />
    ); 
})}


Solution

  • You can assign different variable names when destructuring.

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