2018-10-12 15:37:13 -04:00
|
|
|
---
|
|
|
|
title: Modify an Object Nested Within an Object
|
|
|
|
---
|
2019-07-24 00:59:27 -07:00
|
|
|
# Modify an Object Nested Within an Object
|
|
|
|
|
|
|
|
---
|
|
|
|
## Problem Explanation
|
2018-10-12 15:37:13 -04:00
|
|
|
- Remember the object you want to change is two levels deep, `dot-notation` is easier to use in this instance.
|
|
|
|
- Simply define the object and then use `dot-notation` to access the second object and finally the final element you wish to modify.
|
|
|
|
|
|
|
|
## Example:
|
|
|
|
```javascript
|
|
|
|
let myObject = {
|
2019-07-24 00:59:27 -07:00
|
|
|
level_1: "outside",
|
2018-10-12 15:37:13 -04:00
|
|
|
first_level_object: {
|
2019-07-24 00:59:27 -07:00
|
|
|
level_2: "2 levels deep",
|
2018-10-12 15:37:13 -04:00
|
|
|
second_level_object: {
|
2019-07-24 00:59:27 -07:00
|
|
|
level_3: "3 levels deep"
|
|
|
|
}
|
|
|
|
}
|
2018-10-12 15:37:13 -04:00
|
|
|
};
|
|
|
|
//The following line of code will modify the data found in level_2.
|
2019-07-24 00:59:27 -07:00
|
|
|
myObject.first_level_object.level_2 = "level-2 has been reached";
|
2018-10-12 15:37:13 -04:00
|
|
|
```
|
|
|
|
|
2019-07-24 00:59:27 -07:00
|
|
|
|
|
|
|
---
|
|
|
|
## Solutions
|
|
|
|
|
|
|
|
<details><summary>Solution 1 (Click to Show/Hide)</summary>
|
|
|
|
|
2018-10-12 15:37:13 -04:00
|
|
|
```javascript
|
|
|
|
let userActivity = {
|
|
|
|
id: 23894201352,
|
2019-07-24 00:59:27 -07:00
|
|
|
date: "January 1, 2017",
|
2018-10-12 15:37:13 -04:00
|
|
|
data: {
|
|
|
|
totalUsers: 51,
|
|
|
|
online: 42
|
|
|
|
}
|
|
|
|
};
|
|
|
|
|
|
|
|
// change code below this line
|
|
|
|
userActivity.data.online = 45;
|
|
|
|
// change code above this line
|
|
|
|
|
|
|
|
console.log(userActivity);
|
|
|
|
```
|
2019-07-24 00:59:27 -07:00
|
|
|
</details>
|