web #javascript

Object Destructuring - ES6

Jan 7 '19 · 1 min read · 589

A handy feature introduced in ES6 to help make your code more succinct.

W

hen requiring modules in node.js, as an example, you might choose to save only the methods that you intend to use as variables, rather than the whole module. Previous to ES6, if you wanted to save properties of objects into variables you would have to do something like this:

const property1 = obj.property1;
const property2 = obj.property2;
const property3 = obj.property3;
// etc.

Depending on how many properties you want as variables, this is already starting to look bloated - having to write the property name twice in each case - and a prime candidate for some new syntax. Luckily, the people at Ecma International - who standardised JavaScript - have been way ahead of you.

In ES6, if you want to save object properties as variables with the same name, you can now use the syntax below:

// Equivalent to 
// const property1 = obj.property1;
const {property1} = obj; 

For multiple properties from the same object, you can use a comma separated list:

// Equivalent to 
// const property1 = obj.property1;
// const property2 = obj.property2;
const {property1, property2} = obj;

You can give your new variables different names using the following syntax:

const {property1: p1, property2: p2} = obj;