DEV Community

Cover image for Destructuring Arrays & Objects In JavaScript part-2
Jasvir Singh
Jasvir Singh

Posted on • Edited on

Destructuring Arrays & Objects In JavaScript part-2

In my Last article (Array destructuring Part-1) we learned about array destructuring, If you remember as I explained in my previous article, Destructuring is ES6 feature and its basically a way of unpacking values from an array or an object into separate variables. So in other words destructuring is to break a complex data structure down in to a smaller data structure like a variable.

This article will cover Object Destructuring.

To do object destructuring, we need to create an object.

const restaurant ={
    restaurantName: "Bombay Night",
    location: "james street 52, New York,
    openingHours:{
      mon:{
        open:10,
        close:22,
     },
     fri:{
       open:11,
       close:23,
    },
    sat:{
      open:13,
      close:23,
    },
  },
}

Enter fullscreen mode Exit fullscreen mode

Fundamentals of the Destructuring

we use the curly braces to do object destructure,Then all we have to do is to start with const and provide/define the variable names that exactly match the property names that we want to retrieve from the object. One thing remember in an object the order of elements does not matter,we don't need to skip elements like we did in an array.

const { restaurantName, openingHours } = restaurant;
console.log( restaurantName,openingHours);
// output Bombay Night
// output openingHours:{
      mon:{
        open:10,
        close:22,
     },
     fri:{
       open:11,
       close:23,
    },
    sat:{
      open:13,
      close:23,
    },
  }

Enter fullscreen mode Exit fullscreen mode

So this the fundamentals of the destructuring objects.This is extremely useful especially when we deal with the results of a API, get data from another web application.Data is usually comes in the form of objects then we can destructure it to do further actions.

Switching Property Name

lets Take one step further, suppose if want the variable name to be different from the property name. So here we can do it like this but of course we still need to reference the property names like we did above and we use colon to specify a new variable name.

const {restaurantName: name , openingHours:hours} = restaurant;
console.log(name,hours);
// output Bombay Night
// output openingHours:{
      mon:{
        open:10,
        close:22,
     },
     fri:{
       open:11,
       close:23,
    },
    sat:{
      open:13,
      close:23,
    },
  }

Enter fullscreen mode Exit fullscreen mode

This how we can able to give them new variable name.This is really helpful when dealing with third party data.

Default values

Another useful feature when we are dealing with third party data like an object that we get from somewhere else for example an API call,it can be really useful to have default values for the case that we are trying to read a property that does not exist on the object,so usually then we get an undefined, for example we do not have property name restaurantMenu, if we will try to get this property,this would be undefined because there is no property call restaurantMenu, so we can set default values just like we did in arrays.

const {restaurantName: name , restaurantMenu = [] } = restaurant;
console.log(name,restaurantMenu);
// output Bombay Night
// output here will get empty Array [] instead undefined 
Enter fullscreen mode Exit fullscreen mode

Keep in mind this is really helpful when we don't have hard coded data like we have it above then it is useful to set default values.

Mutating Variables

Next we will talk about mutating variables while destructuring objects so we did that in previous article with Arrays but in objects that works bit differently.

// here we define two variables x and y
let x = 50;
let y = 100;
// here we define one object z with property name x and y
const Z = { x:10, y:50 };

// and now we want to destructure this object
// keep in mind we can't do it like this here, like we did in array, this will throw error
 **{x,y} = z;**

// to destructure this object we need to wrap this destructuring assignment in to parenthesis like this 
({x,y} = z);
console.log(x,y);//output : x = 10  y = 50
Enter fullscreen mode Exit fullscreen mode

Nested objects

Lets say we want create two variables open and close and these should contain the open and close hours for Friday. As we know we have openingHours object which is inside restaurant object then in that object, we have another objects. So Friday is an object inside openingHours object.

//lets say we want retrieve friday 
const {restaurantName,openingHours } = restaurant;
const{fri} = openingHours;
console.log(fri); 
// output : {
       open:11,
       close:23,
    }  

Enter fullscreen mode Exit fullscreen mode

Actually we want two variables one called open and other called close to do this we need to further destructure

 const{fri : {open,close} } = openingHours;
console.log(open,close); 
// output : 11 23

Enter fullscreen mode Exit fullscreen mode

We could of course take this even further and assign different variables to these just like we did above with colon.

const{fri : {open: openTime , close: closeTime} } = openingHours;
console.log(openTime,closeTime); 
// output : 11 23

Enter fullscreen mode Exit fullscreen mode

To learn more about javaScript Destructuring

See you guys! stay safe & keep coding........

Top comments (4)

Collapse
 
hacker4world profile image
hacker4world

Great blog very clear explanation

Collapse
 
jassin82 profile image
Jasvir Singh • Edited

Thanks ! its gives motivation when someone appreciate your work ..... Thanks

Collapse
 
sfbdev profile image
Furkan Bayram

Thanks, this article will be really helpfull to understand this concept.

Collapse
 
jassin82 profile image
Jasvir Singh

Thanks Furkan ! 👍✌️