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)