Destructuring Objects in JavaScript.

In objects we use {} curly braces to destructure. Because this is how we create objects. Then we all have to do is to provide variable names that exactly match the property names of an object we want to destructure.

const restaurant = {name: ‘ bella vista’,restLocation: ‘ chandigarh’,categories: [‘Italian’, ‘Vegetarian ’, ‘Non-vegetarian ’],menu: [‘pizza’, ‘pasta’, ‘garlic bread’],
openingHours: {
thu: {
open: 12,
close: 22
},
fri: {
open: 11,
close: 23,
}
},
orderDelivery: function ({ time = ‘20:00’, address, mainIndex = 2, starterIndex = 1,}) {console.log(`Order received ${this.mainMenu[mainIndex]} , ${this.starterMenu[starterIndex]}, at ${address} time: ${time}`); },}

So here’s an object restaurant. so since in an object order of elements doesn’t matter, we don’t need to manually skip items like we did in array destructuring . we have to simply write the variable names exactly matching to property names in whatever order they are.

for ex:

const {name, menu, restLocation} = restaurant;console.log(name, menu , restLocation);
output :
"bella vista" ['pizza', 'pasta', 'garlic bread'] "chandigarh"

it’s exactly like destructuring with arrays but in arrays we use square brackets [] and in objects we use curly braces {} with property names of object because in objects order of elements doesn’t matter. that’s the fundamental of destructuring objects and it’s very useful. Specially in case of fetching data from API’s and web servers because data in API’s comes in objects.

What if we want variable names different from property names👉

we can do this but we still need reference to property names otherwise javaScript has no way of knowing what we want .

const {name: restaurantName, menu: mainMenu, restLocation: place} = restaurant

this is the way 👆we can name variables from different property names by using the : (colon) and specify new name. It’s very helpful while dealing with third party data or fetching data from api’s , we can set default names and it will be quite useful and easy to understand.

We can set default values to variables while destructuring 👉

for ex: in above object restaurant there’s no property called starterMenu and we are destructuring that it will show undefined, because there’s no property called starterMenu. so in that case we can assign default value:

const {starterMenu = [], menu : mainMenu = []} = restaurant;//👆here we assigned default value as empty array to variables starterMenu = [] and we changed the name of menu property from restaurant object to mainMenu and assigned default value []
console.log(starterMenu, menu);
so the output will be: [] [‘pizza’, ‘pasta’, ‘garlic bread’]if we haven't assigned default value to starterMenu output will be:
undefined [‘pizza’, ‘pasta’, ‘garlic bread’]

It’s very helpful while dealing with third party data or fetching data from api’s, where we don’t know whether the object we are fetching has the exact property we want or not.

Mutating variables while destructuring objects 👉

let a = 34;
let b = 56;
const obj = {a:23 , b:7, c:14}
({a, b} = obj);
console.log(a, b)
output will be: 23 7

we can mutate by wrapping destructuring assignments into parentheses ()

Nested Objects 👉

So in our restaurant object openingHours is an property object and in that object we have fri an object .. as it’s an object in a object or nested objects. We want to retrieve open and close from fri object.

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

We can do destructuring in paramaters passing in functions as an object , so we have no need to pass every single argument as parameter or define every single parameter , we can pass one object as an argument and destructure it.

orderDelivery: function ({ time = ‘20:00’, address, mainIndex = 2, starterIndex = 1,}) {console.log(`Order received ${this.mainMenu[mainIndex]} , ${this.starterMenu[starterIndex]}, at ${address} time: ${time}`);},// 👆this is the method in our restaurant object to deliver order.
here we have passed an object as argument and destructured it instead of defining each parameter every single time, and assigned the default values in case any property is missing from data.
restaurant.orderDelivery({
time: '22:30',
address: 'mohali',
mainIndex: 2,
starterIndex: 1,
});
//👆 this is the object argument we have passed in that orderDelivery method of restaurant object.

So destructuring is very powerful and helpful in JavaScript as it saves lot’s of mess and lines of code.