In modern JavaScript with ES5 and ES6 features, one of the big things is destructuring objects and arrays. You can easily destructure object properties to make new variables but when it comes to destructuring a nested property, it’s a little tricky. This article explains how to destructure a nested property or an object.
Destructuring a Nested Object from Another Object
Let’s assume you have a user’s data with name, age, and address where the address is another object with street number and house number properties. You need to destructure the address which is a nested object. The following code snippet destructures a nested object.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
const simpleObject = { name: "John", age: 22, address: { street: "34th", houseNo: 23 } } const {name, address } = simpleObject console.log(address) // output: {street: "34th", houseNo: 23} |
Destructuring a Nested Property from A Nested Object
What if you want to access streetNo
property, not the entire object? There may be situations where you need only some properties of a nested object. The following code example just destructures the streetNo
not the entire address
object.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
const simpleObject = { name: "John", age: 22, address: { street: "34th", houseNo: 23 } } const {name, address: {street}, } = simpleObject console.log(street) // output : 34th |
Please note that in the above example, address
is null
because the address is not destructured.
Conclusion
There are uses cases where you need to destructure just a few properties from a nested object. You can destructure the nested object as well as just a few properties from the nested object with address: {street},
syntax. You can read more about object destructuring on Mozzila documentation.