Thu Jan 07 2021

How to destructure nested objects using ES6

Destructuring nested objects in JavaScript can be a fun excercise thanks to ES6. Check out the example here and try it yourself!

I’m sure that most of you are familiar with ES6 (if you haven’t, start learning now my budding frontend developer!) and the destructuring assignment that came with it. But I don’t want to tread on any toes here, so let me quickly show you what destructuring is and why it makes us write code that is more DRY (Don't repeat yourself).

The destructuring assignment essentially allows us to unpack values from arrays, or properties from objects, into distinct variables that can be used however we want. Take the below object for example 

1const user = {
2 id: 101,
3 email: "wowza@dev.com",
4};

We can easily console.log the values of the id and email keys easily when we destrucutre and print it like below

1const {
2 id,
3 email
4} = user
5console.log(id, email);

This is all good and nice when the array you have to extract from is quiet simple. But there are many times when it will not be so. I came across such an instance recently when I was working on a project for a client, which is why I am writing this article. So let’s take the below example

1const user = {
2 id: 101,
3 email: "wowza@dev.com",
4 personalInfo: {
5 name: "James",
6 address: {
7 line1: "112",
8 line2: "Independence Road",
9 city: "Poznan",
10 state: "Greater Poland"
11 }
12 }
13};

This object as you can see is slightly more complicated since it has some nested objects inside it. So the objective we have to set ourselves for this lesson is to obtain the values in the line1, line2, city and state keys. 

Here is how we go about destructuring to achieve this 

1const {
2 personalInfo: {
3 address: {
4 line1,
5 line2,
6 city,
7 state
8 }
9 }
10} = user;

And once we console log this with

1console.log(line1, line2, city, state);

We see

1112 Independence Road Poznan Greater Poland

And that's it!

Remember, the key to destructuring nested objects is to carve a path to the key of the value you need. The deeper the nesting the deeper you will have to go. The good thing, however, is that once the destructuring its done, the values are yours to use as you like!

If you found this quick read on destructuring nested objects helpful, please let me know and follow me on my social media channels for more! If not, you can just sign up to my email newsletter below to be notified of any blog post I publish 😊

Comments