🚀 Want to Master Web Development & Java?
Subscribe to Ram N Java for easy, practical coding tutorials!
🔔 Subscribe to Ram N JavaIntroduction: Working with Nested JSON Objects
JSON (JavaScript Object Notation) is one of the most widely used formats to store and transfer data on the web. Often, JSON objects contain inner objects—known as nested JSON objects.
In this guide, you will learn step-by-step how to modify or update values inside nested JSON objects using JavaScript.
1. What Does a Nested JSON Object Look Like?
A nested JSON object contains another object as a value for one of its keys. Let's look at a simple example:
let myData = {
"name": "Ram",
"age": 30,
"cars": {
"car1": "Ford",
"car2": "BMW",
"car3": "Fiat"
}
};
Here, cars is an inner object that holds multiple car models.
2. Modifying Values Using Dot Notation
The cleanest way to access and update nested properties is by chaining dot notation (.).
// Changing car1 from "Ford" to "Maruti" myData.cars.car1 = "Maruti"; console.log(myData.cars.car1); // Output: Maruti
3. Modifying Values Using Bracket Notation
You can also use bracket notation (["property"]). This is useful when key names contain spaces, special characters, or are stored inside variables.
// Changing car2 from "BMW" to "Audi" myData.cars["car2"] = "Audi"; console.log(myData.cars["car2"]); // Output: Audi
Summary
- Use dot notation (
object.nestedObject.key = newValue) for clean and simple updates. - Use bracket notation (
object.nestedObject["key"] = newValue) when property names are dynamic.
No comments:
Post a Comment