DEV Community 👩‍💻👨‍💻

Randy Rivera
Randy Rivera

Posted on

Modifying an Object Nested Within an Object

  • Now let's take a look at a slightly more complex object. Object properties can be nested to an arbitrary depth, and their values can be any type of data supported by JavaScript, including arrays and even other objects.
  • Ex:
let userActivity = {
  id: 28802695164,
  date: 'December 31, 2016',
  data: {
    totalUsers: 99,
    online: 80,
    onlineStatus: {
      active: 67,
      away: 13,
      busy: 8
    }
  }
};
Enter fullscreen mode Exit fullscreen mode
  • userActivity has three properties: id, data, and data (value is an object with its nested structure). We can still use the same notations to access the information we need.
  • To assign the value 18 to the busy property of the nested onlineStatus object, we use dot notation to reference the property:
nestedObject.data.onlineStatus.busy = 18;
Enter fullscreen mode Exit fullscreen mode
  • Now it will look like this:
let userActivity = {
  id: 28802695164,
  date: 'December 31, 2016',
  data: {
    totalUsers: 99,
    online: 80,
    onlineStatus: {
      active: 67,
      away: 13,
      busy: 18
    }
  }
};
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

🤯

"I made 10x faster JSON.stringify() functions, even type safe"

☝️ Must read for JS devs