Changing value of nested object keys in JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

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
raja
Published on 14-Sep-2020 08:07:31
Advertisements