How to modify properties of a nested object in JavaScript?


There are two methods to modify properties of nested objects. One is Dot method and the other is Bracket method. The functionality is same for both the methods, but the only difference is their notation. 

lets' discuss them in detail.

Dot method

Example

In the following example initially the value of property country is England. But using Dot notation the value is changed to India.

Live Demo

<html>
<body>
<script>
   var person;
   var txt = '';
   person = {
      "name":"Ram",
      "age":27,
      "address": {
         "houseno":123,
         "streetname":"Baker street",
         "country":"England"
      }
   }
   document.write("Before change : " + " " + person.address.country);
   person.address.country = "India";
   document.write("</br>");
   document.write("After change : " + " " + person.address.country);
</script>
</body>
</html>

Output

Before change : England
After change : India

Bracket method

Example

In the following example the value of  property 'country' is changed from England to India using Bracket notation

Live Demo

<html>
<body>
<script>
   var person;
   var txt = '';
   person = {
      "name":"Ram",
      "age":27,
      "address": {
         "houseno":123,
         "streetname":"Baker street",
         "country":"England"
      }
   }
   document.write("Before change : " + " " + person.address["country"]);
   person.address.country = "India";
   document.write("</br>");
   document.write("After change : " + " " + person.address["country"]);
</script>
</body>
</html>

Output

Before change : England
After change : India

Updated on: 30-Jul-2019

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements