Object Destructuring in JavaScript

Shivam Gupta
2 min readOct 31, 2018

--

Destructure simply means if we have many keys in an object and need to get these keys in local variables so how to write clean code without repeating same lines.

Lets go quickly, see this example -

var obj = {
name: “Shivam Gupta”,
profession: “Developer”,
address: “India”
}

var getAllData = (obj) => {
// 1st way to get data in local variables
let name = obj.name;
let profession = obj.profession;
let address = obj.address;

console.log(‘name => ‘, name, ‘profession =>’, profession, ‘address => ‘, address )
}

getAllData(obj);

Here we create 3 local variables but we can do it more simplify and remove redundant code and make code more cleaner using ES6 Destructuring.

var getAllData = (obj) => {
// 1st way to get data in local variables
let {name, profession, address} = obj;

console.log(‘name => ‘, name, ‘profession =>’, profession, ‘address => ‘, address )
}

getAllData(obj);

Now Take another example if we want to Destructure nested object —

let person = { 
name: 'Maya',
age: 30,
phone: '123',
address:{
zipcode: 1234,
street: 'k block delhi',
number: 30
}
}

We want to extract only values of zipcode, street, number from person.

let {address: {zipcode, street, number}} = person;console.log(zipcode, street, number); //1234 k block delhi 30

OR

let {zipcode, street, number} = person.address;console.log(zipcode, street, number); //1234 k block delhi 30

How to get sub-object from the object containing some of the keys using Destructure way?

Object Destructuring

This is really just an anonymous function being called instantly. All of this can be found on the Destructuring Assignment page on MDN. Here is an expanded form

Explain Object Destructure

Let's see 1 more cool benefit of Destructuring:

Use Destructure syntax when returning Object when variable name and object keys are same

Thanks, Please clap if you like it! :) Any Question write in the comment section

--

--

Shivam Gupta
Shivam Gupta

Written by Shivam Gupta

Full Stack Engineer (Web/App) working on different JS Technologies & frameworks— Angular, Node, Typescript, Ionic, Firebase, AWS, ElK...Love to write cool stuff

No responses yet