🔹 What are Nested Objects?
A nested object is when an object contains another object as one of its property values.
const myObj = {
name: "John",
age: 30,
myCars: {
car1: "Ford",
car2: "BMW",
car3: "Fiat"
}
};Here:
myObjis the main object.myCarsis a nested object insidemyObj.myCarscontains three properties:car1,car2, andcar3.
🔸How to Access Nested Properties
1. Dot Notation
console.log(myObj.myCars.car2); // Output: BMWThis is the most common and clean way to access nested properties.
You go level by level:
myObj → myCars → car2.
2. Bracket Notation
console.log(myObj.myCars["car2"]); // Output: BMW
console.log(myObj["myCars"]["car2"]); // Output: BMWBracket notation is useful when:
The property name is dynamic (from a variable).
The property name contains spaces or special characters.
3. Using Variables as Keys
let p1 = "myCars";
let p2 = "car2";
console.log(myObj[p1][p2]); // Output: BMWThis is how you access nested properties dynamically using variables.
p1holds"myCars"andp2holds"car2", somyObj[p1][p2]=myObj["myCars"]["car2"].
🧠 Why Use Nested Objects?
Nested objects are useful to:
Represent complex data structures.
Organize related data together (e.g., user profile, car details, settings).