Object properties can contain any kind of value. That includes other objects!
This allows us to organize our data better:
const book = {
title: 'Gone with the Wind',
genre: 'Epic Historical Romance',
author: {
name: 'Margaret Mitchell',
nationality: 'American',
},
};
Creating Nested Objects
We can create nested objects all at once like the example above.
We could also create individual objects and then merge them together:
const margaretMitchell = {
name: 'Margaret Mitchell',
nationality: 'American',
};
const book = {
title: 'Gone with the Wind',
genre: 'Epic Historical Romance',
author: margaretMitchell,
};
Both examples will create an identical object.
Accessing Nested Object Properties
To access the properties inside nested objects, we chain property names together:
const book = {
title: 'Gone with the Wind',
genre: 'Epic Historical Romance',
author: {
name: 'Margaret Mitchell',
nationality: 'American',
},
};
console.log(book.title); // "Gone with the Wind"
console.log(book.author.name); // "Margaret Mitchell"