Accessing Nested Arrays

Accessing Nested Arrays


Hi guys,
So I’m stuck in this exercise can anybody give me a hint and tell me what I’m doing wrong.

Your code so far

// Setup
var myPlants = [
    type: "flowers",
    list: [
    type: "trees",
    list: [

// Only change code below this line

var secondTree = myPLants[1].type[1].list[1]; // Change this line

var secondTree = myPLants[1].list[1];

The property “type” has only only one value - “trees”, a string, not an array.
You have to locate “pine” which is the 2nd value in the “list” array.


Accessing Nested Arrays

The code snippet;

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

So basically the skeleton code looks like this:

Object = [ { name: “value”, name: [ array of 3 string values ] } , { name: “value”, name: [ array of 3 string values ] } ];

Inside the outer array ( [ ]; ) you have two sets of closed curly braces [ { }, { } ] separated with a comma-delimiter.
Now inside each one of the 2 curly braces you have 2 properties with name-value pairs. The second property in both, the ‘list’, just happens to have a nested array with 3 values.

var myPlants // is the Object.

Remember, ‘var’ 'is a keyword and stands for variable. You declare the variable object and name it - ‘myPlants.’ Using the assignment operator (=) you assign to ‘myPlants’ properties on the right of the assignment operator ( = ).

           Syntax:  objectName.propertyName
           Explained like this: myPlants.list
  • An Object is a collection of properties. A property is an association between a name (or key) and a value.
    The properties of an object define the characteristics of the object.

For example; related to the object myPlants ; inside the first set of curly braces the property consists of name(key)/value pair - ‘type: flowers’. The second property name/value pair being - ‘list’ : [ and it’s value(s) are an array with 3 string values.]

So to access the the properties; you do this in two ways;

  1. objectName.propertyName
  2. objectName[“propertyName”]

In the code above you have two ‘myPlant’ items inside the array. Access to them is as follows; The first written as, myPlant[0]. And the second written as, myPlant[1].

(Remember, we always start from the left at the 0 (zero) index of an array.)

Therefore to retrieve the second tree, we code; var secondTree = myPlants[1].list[1];

So remember to access the first myPlants element, would be to access the first element in the array, which using bracket notation is written as - myPlants[0]. To access the second myPlants element in the array would be coded as; myPlants[1]. The same goes for the access for the list array!


I was stuck with this for a long time and your explanation has really helped me. Thank you.