It is similar to array destructuring except that instead of values being pulled out of an array, the properties (or keys) and their corresponding values can be pulled out from an object.
When destructuring the objects, we use keys as the name of the variable. The variable name must match the property (or keys) name of the object. If it does not match, then it receives an undefined value. This is how JavaScript knows which property of the object we want to assign.
In object destructuring, the values are extracted by the keys instead of position (or index).
First, try to understand the basic assignment in object destructuring by using the following example.
const num = {x: 100, y: 200}; const {x, y} = num; console.log(x); // 100 console.log(y); // 200
Let us understand the basic object destructuring assignment.
const student = {name: 'Arun', position: 'First', rollno: '24'}; const {name, position, rollno} = student; console.log(name); // Arun console.log(position); // First console.log(rollno); // 24
Like array destructuring, a default value can be assigned to the variable if the value unpacked from the object is undefined. It can be clear from the following example.
const {x = 100, y = 200} = {x: 500}; console.log(x); // 500 console.log(y); // 200
In the above example, the variables x and y have default values 100 and 200. Then, the variable x is reassigned with a value of 500. But the variable y is not reassigned, so it retains its original value. So, instead of getting 100 and 200 in output, we will get 500 and 200.
We can assign a variable with a different name than the property of the object. You can see the illustration for the same as follows:
const num = {x: 100, y: 200}; const {x: new1, y: new2} = num; console.log(new1); //100 console.log(new2); //200
In the above example, we have assigned the property name as x and y to a local variable, new1, and new2.
if the value of the variable is not assigned when you declare it, then you can assign its value during destructuring. You can see the illustration for the same as follows:
let name, division; ({name, division} = {name: 'Anil', division: 'First'}); console.log(name); // Anil console.log(division); // First
In the above example, it is to be noted that the use of parentheses () around the assignment statement is mandatory when using variable destructuring assignment without a declaration. Otherwise, the syntax will be invalid.
By using the rest operator (…) in object destructuring, we can put all the remaining keys of an object in a new object variable.
Let us try to understand it with an example.
let {a, b, ...args} = {a: 100, b: 200, c: 300, d: 400, e: 500} console.log(a); console.log(b); console.log(args);
A property that is unpacked from an object can be assigned to a variable with a different name. And the default value is assigned to it in case the unpacked value is undefined.
const {a:num1=100, b:num2=200} = {a:300}; console.log(num1); //300 console.log(num2); //200