2018-09-30 23:01:58 +01:00
---
id: 56533eb9ac21ba0edf2244cd
title: Accessing Nested Arrays
challengeType: 1
2019-02-14 12:24:02 -05:00
videoUrl: 'https://scrimba.com/c/cLeGDtZ'
2019-07-31 11:32:23 -07:00
forumTopicId: 16160
2021-01-13 03:31:00 +01:00
dashedName: accessing-nested-arrays
2018-09-30 23:01:58 +01:00
---
2020-11-27 19:02:05 +01:00
# --description--
2018-09-30 23:01:58 +01:00
As we have seen in earlier examples, objects can contain both nested objects and nested arrays. Similar to accessing nested objects, Array bracket notation can be chained to access nested arrays.
2020-11-27 19:02:05 +01:00
2018-09-30 23:01:58 +01:00
Here is an example of how to access a nested array:
2019-05-17 06:20:30 -07:00
```js
var ourPets = [
{
animalType: "cat",
names: [
"Meowzer",
"Fluffy",
"Kit-Cat"
]
},
{
animalType: "dog",
names: [
"Spot",
"Bowser",
"Frankie"
]
}
];
ourPets[0].names[1]; // "Fluffy"
ourPets[1].names[0]; // "Spot"
```
2020-11-27 19:02:05 +01:00
# --instructions--
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
Retrieve the second tree from the variable `myPlants` using object dot and array bracket notation.
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
# --hints--
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
`secondTree` should equal "pine".
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
```js
assert(secondTree === 'pine');
2018-09-30 23:01:58 +01:00
```
2020-11-27 19:02:05 +01:00
Your code should use dot and bracket notation to access `myPlants` .
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
```js
assert(/=\s*myPlants\[1\].list\[1\]/.test(code));
```
2018-09-30 23:01:58 +01:00
2020-11-27 19:02:05 +01:00
# --seed--
## --after-user-code--
```js
(function(x) {
if(typeof x != 'undefined') {
return "secondTree = " + x;
}
return "secondTree is undefined";
})(secondTree);
```
## --seed-contents--
2018-09-30 23:01:58 +01:00
```js
// Setup
var myPlants = [
2018-10-08 01:01:53 +01:00
{
2018-09-30 23:01:58 +01:00
type: "flowers",
list: [
"rose",
"tulip",
"dandelion"
]
},
{
type: "trees",
list: [
"fir",
"pine",
"birch"
]
2018-10-08 01:01:53 +01:00
}
2018-09-30 23:01:58 +01:00
];
// Only change code below this line
var secondTree = ""; // Change this line
```
2020-11-27 19:02:05 +01:00
# --solutions--
2018-09-30 23:01:58 +01:00
```js
var myPlants = [
2018-10-08 01:01:53 +01:00
{
2018-09-30 23:01:58 +01:00
type: "flowers",
list: [
"rose",
"tulip",
"dandelion"
]
},
{
type: "trees",
list: [
"fir",
"pine",
"birch"
]
2018-10-08 01:01:53 +01:00
}
2018-09-30 23:01:58 +01:00
];
// Only change code below this line
var secondTree = myPlants[1].list[1];
```