Nesting Properties
Objects are not limited to storing simple strings or numbers. They can contain other objects (and arrays), allowing you to create deeply nested, complex data structures.
Creating Nested Objects
Here, we’ve nested two object literals within a parent tournament object:
const tournament = {
referee: {
name: "Sally",
age: 25,
},
prize: {
units: "dollars",
value: 100,
},
};
Accessing Nested Data
You can access deeply nested properties by continually chaining the dot (.) operator.
console.log(tournament.referee.name); // Output: "Sally"
console.log(tournament.prize.value); // Output: 100
Practical Example
In most software systems, distinct “entities” (like campaigns, users, or messages) are stored as nested objects.
const campaign = {
name: "Jurassic Campaign",
messageCount: 100,
creator: {
firstName: "Ian",
lastName: "Malcolm",
createdAt: "2023-10-01T09:00:00+00:00"
}
};
function getCampaignCreatorFirstName(campaignData) {
// Chain through the parent object to reach the inner property
return campaignData.creator.firstName;
}
console.log(getCampaignCreatorFirstName(campaign)); // Output: "Ian"