Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Changing value of nested object keys in JavaScript
In JavaScript, you can change nested object values using dot notation and square brackets. This is useful when working with complex data structures containing multiple levels of nesting.
Syntax
// Using dot notation object.property.nestedProperty = newValue; // Using square brackets object['property']['nestedProperty'] = newValue; // Mixed approach object.property['nestedProperty'] = newValue;
Example: Changing Nested Object Values
var details = {
"customer": {
"customerDetails": {
"otherDetails": [
{
"customerDetails": {
"isMarried": false
}
},
{
"customerDetails": {
"isMarried": false
}
},
{
"customerDetails": {
"isMarried": false
}
}
]
}
}
};
console.log("Original values:");
for (var index = 0; index < details.customer.customerDetails['otherDetails'].length; index++) {
console.log("isMarried: " + details.customer.customerDetails['otherDetails'][index].customerDetails['isMarried']);
}
console.log("\nChanging all values to true...");
for (var index = 0; index < details.customer.customerDetails['otherDetails'].length; index++) {
details.customer.customerDetails['otherDetails'][index].customerDetails['isMarried'] = true;
}
console.log("\nUpdated values:");
for (var index = 0; index < details.customer.customerDetails['otherDetails'].length; index++) {
console.log("isMarried: " + details.customer.customerDetails['otherDetails'][index].customerDetails['isMarried']);
}
Original values: isMarried: false isMarried: false isMarried: false Changing all values to true... Updated values: isMarried: true isMarried: true isMarried: true
Alternative Approaches
You can use different notation styles for the same result:
// Method 1: Pure dot notation (when property names allow it)
var obj = {
level1: {
level2: {
value: "original"
}
}
};
obj.level1.level2.value = "changed";
console.log("Method 1:", obj.level1.level2.value);
// Method 2: Mixed notation
obj.level1['level2'].value = "mixed approach";
console.log("Method 2:", obj.level1['level2'].value);
// Method 3: Pure bracket notation
obj['level1']['level2']['value'] = "bracket approach";
console.log("Method 3:", obj['level1']['level2']['value']);
Method 1: changed Method 2: mixed approach Method 3: bracket approach
Key Points
- Use dot notation when property names are valid JavaScript identifiers
- Use square brackets when property names contain spaces, special characters, or are dynamic
- Both methods can be mixed in the same expression
- Always ensure the nested path exists to avoid "Cannot read property" errors
Conclusion
Changing nested object values in JavaScript is straightforward using dot notation and square brackets. Choose the appropriate syntax based on your property names and use cases.
Advertisements
