Objects are one of the most important parts of JavaScript.
But what happens when objects contain other objects inside them?
Thatβs where nested objects come in! π
In this article, weβll cover everything about nested objects in a simple and easy way:
- π Accessing nested properties
- βοΈ Adding and modifying values
- ποΈ Deleting values
- π’ Working with deeply nested objects
- β Optional chaining (safe access)
- π Looping through nested objects
- β Checking for properties
- π οΈ Adding methods to objects
- π¦ Cloning nested objects
Letβs get started! π
1. What is a Nested Object? π€
A nested object is simply an object inside another object.
const user = {
name: "Usman",
age: 22,
address: {
street: "123 Main St",
city: "Lahore",
country: "Pakistan"
}
};
`
Here:
-
user
is the main object -
address
is a nested object insideuser
2. Accessing Nested Properties π
We use dot notation (.
) to access properties.
js
console.log(user.address.city); // Lahore
β
First go inside user
β then into address
β then city
.
3. Adding and Modifying Properties βοΈ
We can change values or add new ones.
`js
// Changing a value
user.address.city = "Karachi";
console.log(user.address.city); // Karachi
// Adding a new property
user.address.zipCode = "12345";
console.log(user.address.zipCode); // 12345
`
4. Deleting Properties ποΈ
We can use the delete
keyword.
js
delete user.address.street;
console.log(user.address.street); // undefined
Now street
is removed from the object.
5. Deeply Nested Objects π’
Objects can go many levels deep!
`js
const company = {
name: "Texnology Inc.",
address: {
city: "Islamabad",
office: {
floor: 5,
room: "501A"
}
}
};
console.log(company.address.office.room); // 501A
`
We go step by step: company β address β office β room
.
6. Optional Chaining β (Safe Access)
Sometimes a property might not exist.
If we try to access it directly, it will throw an error β.
js
console.log(company.address.warehouse.room);
// β Error: Cannot read property 'room' of undefined
β
The fix is optional chaining (?.
):
js
console.log(company.address.warehouse?.room); // undefined (no error)
7. Looping Through Nested Objects π
We can use a for...in
loop.
js
${key}: ${user.address[key]}`);
for (const key in user.address) {
console.log(
}
// city: Karachi
// country: Pakistan
// zipCode: 12345
`
8. Checking if a Property Exists β
Two ways:
js
console.log("city" in user.address); // true
console.log(user.address.hasOwnProperty("street")); // false
9. Adding Methods to Objects π οΈ
Objects can also have functions (methods).
js
${this.address.street}, ${this.address.city}, ${this.address.country}`;
user.getFullAddress = function() {
return
};
console.log(user.getFullAddress());
// undefined, Karachi, Pakistan (street was deleted earlier)
// Fix: Add street back
user.address.street = "123 Main St";
console.log(user.getFullAddress());
// 123 Main St, Karachi, Pakistan
`
10. Cloning Nested Objects π¦
If we copy objects normally, they share the same reference (changes affect both).
To create a deep clone, we can use JSON methods.
`js
const clonedUser = JSON.parse(JSON.stringify(user));
clonedUser.name = "Ali";
clonedUser.address.city = "Istanbul";
console.log(user.name); // Usman
console.log(user.address.city); // Karachi
console.log(clonedUser.name); // Ali
console.log(clonedUser.address.city); // Istanbul
`
β
Now changes in clonedUser
do not affect user
.
β οΈ Limitation: This method doesnβt clone functions or special objects like Date.
For advanced cases, use Lodashβs _.cloneDeep()
.
π― Final Summary
- Nested objects = objects inside objects
- Use
.
to access properties - Use
delete
to remove properties - Use
?.
(optional chaining) for safe access - Loop through properties with
for...in
- Check if a property exists with
"key" in obj
- Add methods for object-specific actions
- Use JSON methods or Lodash to clone safely
π‘ By understanding nested objects, youβll be more confident working with real-world data (like API responses, configs, or databases).
π₯ Keep practicing and youβll master them in no time!
π¬ Question for you:
Have you ever faced errors like "Cannot read property of undefined" while working with objects? How did you fix it? Share in the comments π
`
Top comments (0)