How to destructure the nested objects in javascript?

Object destructuring is a very cool feature of ES6. Some of us are tired of using dot notation for accessing object properties. Object drestructuring made the code cleaner and more readable. But in some cases, if we don’t know how to use it properly we may run into unexpected issues:

First of all try to restructure the name from userObj.

 const userObj = {
     name: 'Joe Smith',
     age: 20
 };
 const {name} = userObj;
 console.log(name); // Joe Smith

Now we want to drestructure name from userObj and assign it to a different variable.

 const userObj = {
     name: 'Joe Smith',
     age: 20
 };
 const {name: username} = userObj;
 console.log(username); // Joe Smith

We know that destructuring works with nested objects too. Let’s check an example of destructuring with nested object.

 const userObj = {
     name: 'Joe Smith',
     age: 20,
     education: {
         degree: 'Honours'
     }
 };
 const {education: {degree}} = userObj;
 console.log(degree); // Honours

If the nested object property is missing we get TypeError like below:

 const userObj = {
     name: 'Joe Smith',
     age: 20
 };
 const {education: {degree}} = userObj;
 console.log(degree); // Uncaught TypeError:

How to handle when the nested object property is missing?

 const userObj = {
     name: 'Joe Smith',
     age: 20
 };
 const {education: {degree} = {}} = userObj;
 console.log(degree);
Share