109 lines
2.5 KiB
Markdown
109 lines
2.5 KiB
Markdown
|
---
|
||
|
id: 56533eb9ac21ba0edf2244cd
|
||
|
title: Accessing Nested Arrays
|
||
|
challengeType: 1
|
||
|
guideUrl: 'https://guide.freecodecamp.org/certificates/access-array-data-with-indexes'
|
||
|
---
|
||
|
|
||
|
## Description
|
||
|
<section id='description'>
|
||
|
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.
|
||
|
Here is an example of how to access a nested array:
|
||
|
<blockquote>var ourPets = [<br> {<br> animalType: "cat",<br> names: [<br> "Meowzer",<br> "Fluffy",<br> "Kit-Cat"<br> ]<br> },<br> {<br> animalType: "dog",<br> names: [<br> "Spot",<br> "Bowser",<br> "Frankie"<br> ]<br> }<br>];<br>ourPets[0].names[1]; // "Fluffy"<br>ourPets[1].names[0]; // "Spot"</blockquote>
|
||
|
</section>
|
||
|
|
||
|
## Instructions
|
||
|
<section id='instructions'>
|
||
|
Retrieve the second tree from the variable <code>myPlants</code> using object dot and array bracket notation.
|
||
|
</section>
|
||
|
|
||
|
## Tests
|
||
|
<section id='tests'>
|
||
|
|
||
|
```yml
|
||
|
- text: <code>secondTree</code> should equal "pine"
|
||
|
testString: 'assert(secondTree === "pine", "<code>secondTree</code> should equal "pine"");'
|
||
|
- text: Use dot and bracket notation to access <code>myPlants</code>
|
||
|
testString: 'assert(/=\s*myPlants\[1\].list\[1\]/.test(code), "Use dot and bracket notation to access <code>myPlants</code>");'
|
||
|
|
||
|
```
|
||
|
|
||
|
</section>
|
||
|
|
||
|
## Challenge Seed
|
||
|
<section id='challengeSeed'>
|
||
|
|
||
|
<div id='js-seed'>
|
||
|
|
||
|
```js
|
||
|
// Setup
|
||
|
var myPlants = [
|
||
|
{
|
||
|
type: "flowers",
|
||
|
list: [
|
||
|
"rose",
|
||
|
"tulip",
|
||
|
"dandelion"
|
||
|
]
|
||
|
},
|
||
|
{
|
||
|
type: "trees",
|
||
|
list: [
|
||
|
"fir",
|
||
|
"pine",
|
||
|
"birch"
|
||
|
]
|
||
|
}
|
||
|
];
|
||
|
|
||
|
// Only change code below this line
|
||
|
|
||
|
var secondTree = ""; // Change this line
|
||
|
|
||
|
```
|
||
|
|
||
|
</div>
|
||
|
|
||
|
|
||
|
### After Test
|
||
|
<div id='js-teardown'>
|
||
|
|
||
|
```js
|
||
|
console.info('after the test');
|
||
|
```
|
||
|
|
||
|
</div>
|
||
|
|
||
|
</section>
|
||
|
|
||
|
## Solution
|
||
|
<section id='solution'>
|
||
|
|
||
|
|
||
|
```js
|
||
|
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];
|
||
|
```
|
||
|
|
||
|
</section>
|