I need to access a specific element from an object that I have nested within an array, I'm using react functional components.
const accordionItems = [
{ id: 'Releases',
items: [
{item: '123 / first show / 14/3/19', data: track1},
{item: '456 /second show / 31/3/19', data: track2},
{item: '789 / third show / 7/4/19', data: track3} ]
},
{ id: 'Radio',
items: [
{item: '123 / first show / 14/3/19', data: track1},
{item: '456 /second show / 31/3/19', data: track2},
{item: '789 / third show / 7/4/19', data: track3} ]
},
{ id: 'Contact',
items: [
{item: '123 / first show / 14/3/19', data: track1},
{item: '456 /second show / 31/3/19', data: track2},
{item: '789 / third show / 7/4/19', data: track3} ]
}
];
That is the code where my objects are stored. I need to access the 'data' of each one specifically to feed to a parameter of an audio player.
My attempt to do this is below:
<AudioPlayer
src={accordionItems[1].items.data[1]}
/>
I followed the syntax that I researched from a few other questions on here but it seems to send the error of:
Cannot read property '1' of undefined
To my knowledge accordionItems holds three objects which can be accessed through accordionItems[x] and from there you enter the items array and note which data point is to be fed to the source of the audio player.
Does anyone have a solution to help me access this specific data point? Most of the answers that I've researched involved using the map function which I don't think will be appropriate in the long term for how I'm aiming to build this application.
Thanks!
Your issue here is the way you access the data in the actual array.
Let's destructure your query: accordionItems[1].items.data[1]
First of all, accordionItems[1]
is correct because accordionItems
is an array and you can just pick element 1
out of it.
They you access items
, which is fine as well, but you can't take data
from items
like that since items
is an array.
What you want as a final result is accordionItems[1].items[1].data