Introduction
Nested objects are objects inside other objects. They help organize complex data in a structured and readable way. This is useful when working with real world data such as user profiles, products, or company information.
What are Nested Objects
A nested object is created when a property of an object contains another object as its value. This allows grouping related data together.
Example
const user = {
name: "Ali",
age: 20,
address: {
city: "Lahore",
country: "Pakistan"
}
};
In this example address is a nested object inside the user object.
Accessing Nested Objects
You can access values inside nested objects using dot notation or bracket notation.
console.log(user.address.city);
console.log(user["address"]["country"]);
Both methods return the values stored inside the nested object.
Adding Data to Nested Objects
You can add new properties to nested objects easily.
user.address.zipCode = "54000";
Updating Nested Object Values
Values inside nested objects can also be updated.
user.address.city = "Karachi";
Deleting Properties
You can remove properties from nested objects using the delete keyword.
delete user.address.country;
Why Use Nested Objects
Nested objects help manage complex data
They improve code organization
They make data easier to understand
They are useful in APIs and databases
Real World Example
Nested objects are commonly used in applications like ecommerce websites where product details include category pricing and supplier information inside one object.
Conclusion
Nested objects are an important concept in JavaScript for handling structured data. Learning how to create access and modify them will help you build more advanced applications.