Stuck in Accessing Nested Arrays?

hi again! stuck in this excercise and i was wondering if someone could give me a hint of how to solve this?

anyone that could please give me a hint? :slight_smile:

Hi Brian, Try to read the question again very carefully. if you are still stuck look at the example in the previous challenge. The clue is the answer to your previous challenge.

Clue: The answer follows the same format as in the example.

Hope this helps.

1 Like

look at the object … what you see first is a [ so your accessing an array then you see { which shows you its a array with objects
so to access a array we use numbers in brackets eg
myPlants[0] … this would return {type:‘flowers’,list:[‘rose’,‘tulip’,‘dandelion’]}
to access objects we use the key with a . eg .type
so we would put that together myPlants[0].type and we would get back flowers
so if we did myPlants[0].list … we get back [‘roses’,‘tulip’,‘dandelion’]
if we wanted a individual item from list rather than an array returned we have to access it and as its a array we use array notation again eg [num] eg myPlants[0].list[1] … gives us tulip.
think i gave you enough there to sort out this problem … also later on doing projects like weather app and wikipedia and others require accessing objects with arrays containing objects containg arrays so getting a good understanding of accessing these and pulling information out is very important so practice practice till you are very comfortable doing it .

2 Likes

thank you! I managed to finally solve it!

You’ll find this is a very common pattern in JavaScript, to have an array of objects where each may contain complex data types. Sometimes decomposing the data structure makes it easier to reason about. For example, you can grab the first element of the object listing types of flowers like so:

var firstPlantType = myPlants[0];
var listOfFlowers = firstPlantType.list;
var rose = listOfFlowers[0];

An array always begins at 0 in JavaScript. With experience it will become second nature. If you haven’t already, you’ll learn how to iterate over object properties and array elements rather than grabbing each one individually, which is tedious and ultimately not necessary usually.

Have fun!

2 Likes

Thanks John for your very clear and logical explanation. I cracked it!! Prior to coming across you, I spent 1.5 hours trying to work this one out!!

Warm wishes

Bybreen

1 Like

// Setup
var myPlants = [
{
type: “flowers”,
list: [
“rose”,
“tulip”,
“dandelion”
]
},
{
type: “trees”,
list: [
“fir”,
“pine”,
“birch”
]
}
];

// Only change code below this line

var secondTree = myPlants[1].list[1]; // “pine” Change this line

hi JohnL3, what would be the array notation if use “list 2” as key name instead of list? Thanks !

if the object key has a space inside you need to use bracket notation and pass in the property name as a string, obj["list 2"]