90 lines
2.2 KiB
Markdown
90 lines
2.2 KiB
Markdown
|
---
|
||
|
id: 56533eb9ac21ba0edf2244cc
|
||
|
title: Accessing Nested Objects
|
||
|
challengeType: 1
|
||
|
guideUrl: 'https://guide.freecodecamp.org/certificates/accessing-nested-objects-in-json'
|
||
|
---
|
||
|
|
||
|
## Description
|
||
|
<section id='description'>
|
||
|
The sub-properties of objects can be accessed by chaining together the dot or bracket notation.
|
||
|
Here is a nested object:
|
||
|
<blockquote>var ourStorage = {<br> "desk": {<br> "drawer": "stapler"<br> },<br> "cabinet": {<br> "top drawer": { <br> "folder1": "a file",<br> "folder2": "secrets"<br> },<br> "bottom drawer": "soda"<br> }<br>};<br>ourStorage.cabinet["top drawer"].folder2; // "secrets"<br>ourStorage.desk.drawer; // "stapler"</blockquote>
|
||
|
</section>
|
||
|
|
||
|
## Instructions
|
||
|
<section id='instructions'>
|
||
|
Access the <code>myStorage</code> object and assign the contents of the <code>glove box</code> property to the <code>gloveBoxContents</code> variable. Use bracket notation for properties with a space in their name.
|
||
|
</section>
|
||
|
|
||
|
## Tests
|
||
|
<section id='tests'>
|
||
|
|
||
|
```yml
|
||
|
- text: <code>gloveBoxContents</code> should equal "maps"
|
||
|
testString: 'assert(gloveBoxContents === "maps", "<code>gloveBoxContents</code> should equal "maps"");'
|
||
|
- text: Use dot and bracket notation to access <code>myStorage</code>
|
||
|
testString: 'assert(/=\s*myStorage\.car\.inside\[\s*("|")glove box\1\s*\]/g.test(code), "Use dot and bracket notation to access <code>myStorage</code>");'
|
||
|
|
||
|
```
|
||
|
|
||
|
</section>
|
||
|
|
||
|
## Challenge Seed
|
||
|
<section id='challengeSeed'>
|
||
|
|
||
|
<div id='js-seed'>
|
||
|
|
||
|
```js
|
||
|
// Setup
|
||
|
var myStorage = {
|
||
|
"car": {
|
||
|
"inside": {
|
||
|
"glove box": "maps",
|
||
|
"passenger seat": "crumbs"
|
||
|
},
|
||
|
"outside": {
|
||
|
"trunk": "jack"
|
||
|
}
|
||
|
}
|
||
|
};
|
||
|
|
||
|
var gloveBoxContents = undefined; // Change this line
|
||
|
|
||
|
```
|
||
|
|
||
|
</div>
|
||
|
|
||
|
|
||
|
### After Test
|
||
|
<div id='js-teardown'>
|
||
|
|
||
|
```js
|
||
|
console.info('after the test');
|
||
|
```
|
||
|
|
||
|
</div>
|
||
|
|
||
|
</section>
|
||
|
|
||
|
## Solution
|
||
|
<section id='solution'>
|
||
|
|
||
|
|
||
|
```js
|
||
|
var myStorage = {
|
||
|
"car":{
|
||
|
"inside":{
|
||
|
"glove box":"maps",
|
||
|
"passenger seat":"crumbs"
|
||
|
},
|
||
|
"outside":{
|
||
|
"trunk":"jack"
|
||
|
}
|
||
|
}
|
||
|
};
|
||
|
var gloveBoxContents = myStorage.car.inside["glove box"];
|
||
|
```
|
||
|
|
||
|
</section>
|