DEV Community

Gayan Prasanna
Gayan Prasanna

Posted on

JS ES6 Object Destructuring

Intro

Object De-structuring is available to easily breakdown an object to variable since the release of ES6.Before de-structuring, an object's property should be assigned to a variable separately.

const  user = {
        name:'John',
        age:36,
        address:{
            city:'NY',
            country:'USA'
        }
}
const  name = user.name;
const  city = user.address.city; 
Enter fullscreen mode Exit fullscreen mode

Using Destructure

When object de-structuring, we may use brackets with relevant properties that we may want to de-structure.If a property is in a nested object, it should follow that order also.Whenever we need to rename the variable which is going to restructure, we can add that after a colon.See below example

const user = {
   name:'John',
   age:36,
   address:{
       city:'NY',
       country:'USA'
   }
}
const {name,age,address:{city:cityName}} = user;
console.log(name,age,cityName)
Enter fullscreen mode Exit fullscreen mode

Here in the line of const {name,age,address:{city:cityName}} = user; , we de-structure name age as their property name appears in the user object.In order to get city out od the user object, we've to go inside the address object inside the user object.So the same kind of syntax apply there.In that case you may see address:{city:cityName} . here the city:cityName declares a variable city as cityName.so whenever we want to address the city we use cityName hereafter.

Using Spread (...) Operator

We may want to copy several properties as variable and other remaining one's as a whole new object.We can acheive that like below with spread operator

const user = {
  name:'John',
  age:36,
  address:{
      city:'NY',
      country:'USA'
      }
  }
  const {name,age,...rest} = user;
  console.log(name,age,rest)
Enter fullscreen mode Exit fullscreen mode

In here the ...rest part takes the remaining part of the user object which was not de-structured and creates a variable with them called rest

Shallow Copying an object with De-structuring

We all know that Objects in JS are immutable by design.So occasionally we may want to make clones of object(s).Following syntax creates a clone of the user object. p.s : This will only create a shallow copy,If want to create deep copy, may want to use load ash's _.coneDeep(obj) or JSON.parse(JSON.stringify(obj)) or any other library method or native method

const user = {
        name:'John',
        age:36,
        address:{
            city:'NY',
            country:'USA'
        }
}
const userClone = {...user};
console.log(userClone);
Enter fullscreen mode Exit fullscreen mode

Top comments (0)