DEV Community

Usama
Usama

Posted on

JavaScript Nested Objects Made Simple ๐Ÿงฉ

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"
  }
};
Enter fullscreen mode Exit fullscreen mode


`

Here:

  • user is the main object
  • address is a nested object inside user

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
for (const key in user.address) {
console.log(
${key}: ${user.address[key]}`);
}

// 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
user.getFullAddress = function() {
return
${this.address.street}, ${this.address.city}, ${this.address.country}`;
};

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)