Nested objects help organize related information inside other objects, like boxes inside boxes. This makes data easier to find and use.
0
0
Nested objects in Javascript
Introduction
When you want to store details about a person, including their address and contact info inside one object.
When you have a product with multiple features and specifications grouped together.
When you want to represent a menu with categories and items inside each category.
When you need to keep track of a book with chapters and each chapter has pages.
When you want to model a company with departments and each department has employees.
Syntax
Javascript
const obj = {
key1: value1,
key2: {
nestedKey1: nestedValue1,
nestedKey2: nestedValue2
}
};Objects can hold other objects as values, creating layers.
You access nested values by chaining keys with dot notation or brackets.
Examples
This object has a nested object
address inside person.Javascript
const person = { name: "Alice", address: { city: "Wonderland", zip: "12345" } };
Here,
specs is a nested object holding product details.Javascript
const product = { id: 101, specs: { weight: "1kg", color: "red" } };
This shows multiple nested objects inside
menu for different meals.Javascript
const menu = { breakfast: { item1: "Pancakes", item2: "Coffee" }, lunch: { item1: "Sandwich", item2: "Juice" } };
Sample Program
This program creates a user object with nested profile and contact objects. It then prints the user's info by accessing nested keys.
Javascript
const user = { username: "bob123", profile: { firstName: "Bob", lastName: "Smith", contact: { email: "bob@example.com", phone: "555-1234" } } }; console.log(`User: ${user.username}`); console.log(`Name: ${user.profile.firstName} ${user.profile.lastName}`); console.log(`Email: ${user.profile.contact.email}`); console.log(`Phone: ${user.profile.contact.phone}`);
OutputSuccess
Important Notes
You can use either dot notation (obj.key) or bracket notation (obj["key"]) to access nested values.
Be careful if a nested object might not exist; accessing deeper keys without checking can cause errors.
Nested objects help keep data organized but too many layers can make code harder to read.
Summary
Nested objects store objects inside other objects to organize data.
Access nested values by chaining keys with dots or brackets.
Use nested objects to group related information clearly.