ES6 - Destructure Object

ES6 JavaScript

In this ES6 tutorial we will learn to destructure object.

In the previous tutorial we learned How to destructure array.

Destructuring assignment syntax helps us to unpack values from arrays and properties from objects into distinct variables.

If you want to learn how to destructure arrays then watch my destructure array YouTube video.

Destructuring object into distinct variables by its properties name

Let's say we have an object that consists of two fields username and score and we want to assign the values of those two fields to variables username and score respectively. So, we will write something like the following.

const details = { username: "janedoe", score: 10 };
const { username, score } = details;
console.log(username); // 'janedoe'
console.log(score); // 10

Note! When destructuring objects into distinct variables we use the property names as variable names. But this is not alway the case.

Destructuring object into distinct variables, different from their properties name

Let's say we have the same object like above and this time we want to take the username value and assign it to x and score value and assign it to y. To achieve this destructuring we have to write the following code.

const details = { username: "janedoe", score: 10 };
const { username: x, score: y } = details;
console.log(x); // 'janedoe'
console.log(y); // 10

Note! In the above code we are destructuring the details object and picking the username field and saving its value in variable x and score field and saving its value in variable y.

Destructuring some properties of an object

Let's say we have an object and we want to pick some properties and leave the rest. For this we can selectively destructure the object and pick only the needed fields like the following.

const details = { username: "janedoe", score: 10, isOnline: true, level: 2 };
const { username, isOnline } = details;
console.log(username); // 'janedoe'
console.log(isOnline); // true

In the above code we are picking only the username and isOnline properties of the details object.

Destructuring one property of an object and save it in one variable and rest in another

Let's say we have the same object like above and we want to pick the username property in one variable and rest of the properties in another variable.

const details = { username: "janedoe", score: 10, isOnline: true, level: 2 };
const { username, ...rest } = details;
console.log(username); // 'janedoe'
console.log(rest); // { score: 10, isOnline: true, level: 2 }

The above code will take the value of the username property of the details object and save it in the username variable. The rest variable gets the rest of the properties of the details object.