As JavaScript developers you are working a lot with objects and let's face it, manipulating objects wasn't the most convenient thing in JavaScript. ES6 is about to change this. Today we are going to discuss how to destructure objects using ES6.
Before however let's take a look at a sample object and see what we'd do now, using ES5:
var person = {
name: 'Joe',
age: 21,
married: true,
hobbies: ['football', 'tennis', 'cooking']
};
In order to extract some information and store them as variables we'd probably do:
var name = person.name;
var age = person.age;
// so on
This is a slightly laborous exercise, with ES6, utilising object destructuring we can very simply do:
var {name, age} = person;
The above line will automatically create both a name
and an age
variable. If we want we can also have different names then the property name from the object for the variables:
var {myName: name, myAge: age} = person;
This will create myName
and myAge
variables with the right values.
And finally, we can also desctructure arrays using the same notation:
var {name, age, hobbies: [first, second]} = person;
You could now easily access these variables, for example console.log(first)
would return 'football'.