Changing value of nested object keys in JavaScript


For this, use dot(.) notation along with square brackets ([]).

Example

var details = {
   "customer": {
      "customerDetails": {
         "otherDetails": [
            {
               "customerDetails": {
                  "isMarried": false
               },
            },
            {
               "customerDetails": {
                  "isMarried": false
               },
            },
            {
               "customerDetails": {
                  "isMarried": false
               }
            }
         ]
      }
   }
}
console.log("All values are set to true=");
for (var index = 0; index < details.customer.customerDetails['otherDetails'].length; index++) {
   details.customer.customerDetails['otherDetails'][index].customerDetails['isMarr
   ied'] = true;
}
for (var index = 0; index < details.customer.customerDetails['otherDetails'].length; index++) {
   console.log("isMarried:"+details.customer.customerDetails['otherDetails'][index
   ].customerDetails['isMarried']);
}

To run the above program, you need to use the following command −

node fileName.js.

Here, my file name is demo186.js.

Output

This will produce the following output −

PS C:\Users\Amit\javascript-code> node demo186.js
All values are set to true=
isMarried:true
isMarried:true
isMarried:true

Updated on: 14-Sep-2020

405 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements