You have no excuses now, use this free credit to launch your projects now on Digital Ocean, you're free to spend it whenever you want within the following 60 days.
Table of contents
Destructuring nested objects in Javascript
Destructuring nested objects in Javascript
In the previous posts I briefly explained how to perform a destructuring of objects in Javascript , but in most cases we will not be lucky enough to work with flat objects, but we will find nested objects with several levels of depth. Will we have to settle for forgetting about this feature and do the job explicitly assigning a constant to each object? Luckily Javascript allows us to work with the destructuring of nested objects.
Let’s create an example object to test.
const user = {
userIsLoggedIn: true,
data: {
email: "[email protected]",
name:"Isabel",
lastName:"Allende",
location:{
state: "Lima",
country: "Peru",
postalCode: "15048"
}
}
}
Let’s first get the userIsLoggedIn property
const { userIsLoggedIn } = user
userIsLoggedIn
true
¿How to destructure nested properties?
But what if we now want to assign the state property? To achieve this, let’s first think about the structure of the object. Our object has three levels; in the first one, there are userIsLoggedIn and data; in the second one, email, name, lastName and location; in the third level, the properties state, country and postalCode. It is in this last level where is the property that we are trying to destructure.
const user = {
userIsLoggedIn: true,
data: {
email: "[email protected]",
name:"Isabel",
lastName:"Allende",
location:{
state: "Lima",
country: "Peru",
postalCode: "15048"
}
}
}
The first level is data, so we will place a colon “:” there and continue descending to the desired level. Let’s leave the rest pending by assigning a “{…}”. **If you are following this example, do not press ENTER until the end.
const {data:{...}}
The second level leading to our state property is location. So we extend our previous assignment:
const {data:{location:{...}}}
Our property state is at the third level, so we do not have to go down any further, we simply place the constant below.
const {data: {location:{state}}}=user
state
"Lima"
Now you can hit ENTER, when you access the state constant, you will see that it refers to the state property, nested in the object.
How to destructure more than one property?
The previous example was not so complicated, but what if instead of a single property we want to destructure the value of userIsLoggedIn, email and state.
To do the above it would be enough to locate in which level are the properties that we want to destructure and include them in the appropriate level in our passed code statement:
const {userIsLoggedIn, data: {email, location:{state}}}=user
userIsLoggedIn
true
email
"[email protected]"
state
"Lima"
In the next post I will talk about how to assign default values when destructuring objects .