Introduction
Object Destructuring is an ES6 feature that allows us to extract one or many properties of an array or an object with a concise syntax. We can read an entire object structure in a single instruction, that makes it easy to read. More features are also packed with object destructuring : I will talk about some of them in this post.
Extract a property from an object
Let's take the following object:
const user = {
name: 'Estelle',
login: 'estellepicq',
role: 'admin',
job: 'dev'
};If we wanted to extract name and login from the user object in order to assign them in new variables, in a pre-ES6 environment, we would write:
var name = user.name;
var login = user.login;
console.log(name); // ‘Estelle’
console.log(login); // ‘estellepicq’With destructuring, we can write:
const { name, login } = user;
console.log(name); // ‘Estelle’
console.log(login); // ‘estellepicq’That way, we can extract only the wanted properties, in a single line of code.
If the property does not exist, the new variable will be undefined:
const { name, login, age } = user;
console.log(name); // 'Estelle'
console.log(login); // 'estellepicq'
console.log(age); // undefinedIt works the same for arrays:
const fruits = ['apple', 'banana', 'watermelon', 'papaya'];
const [ firstFruit, secondFruit ] = fruits;
console.log(firstFruit); // 'apple'
console.log(secondFruit); // 'banana'Rename a property
Let's take the previous example and say that we want to extract the information contained in login, and assign it to a new variable username:
const { login: username } = user;
console.log(username); // ‘estellepicq’We gave an alias to login and created a new variable username which contain the information.
Give a default value
We saw that if the property was missing, the new variable was undefined. If needed, we can assign a default value.
const { age = 20 } = user;
console.log(age); // 20Conclusion
Object destructuring is a powerful feature allowing us to extract properties from an object and concisely assign them to variables, and I encourage you to use it!
Sources:
https://hacks.mozilla.org/2015/05/es6-in-depth-destructuring/