Enjoying this tutorial?
Subscribe to Ram N Java on YouTube for simple, beginner-friendly coding tutorials and practical guides!
Subscribe NowUnderstanding Nested JSON Objects
In real-world web applications and API responses, data is rarely flat. Often, a value inside a JSON object is another object itself. This structure is called a nested JSON object.
Sample Nested JSON Object
Consider this user profile where contact information is grouped into an inner object:
const userProfile = {
"id": 101,
"name": "Alex",
"contact": {
"email": "alex@example.com",
"city": "Chicago"
}
};
Accessing Nested Properties
You can retrieve nested properties using either dot notation or bracket notation:
- Dot notation: Chaining property names together (e.g.,
userProfile.contact.city). - Bracket notation: Passing keys as strings (e.g.,
userProfile["contact"]["city"]).
// Using dot notation
let city = userProfile.contact.city;
// Using bracket notation
let email = userProfile["contact"]["email"];
console.log("City: " + city);
console.log("Email: " + email);
Key Takeaway
Dot notation is concise and clean when you know property names ahead of time. Use bracket notation when property keys are dynamic or stored in variables.
No comments:
Post a Comment