Destructuring allows you to extract individual values from an object into variables or constants:
const user = { name: "Alexander", age: 33, email: "email@gmail.com" }; let { name, email } = user;//we indicate the required variables and the object from which they are taken console.log(name); //Alexander console.log(email);//email@gmail.com
We can specify that we want to get the object’s property values into variables/consts with a different name:
const user = { name: "Alexander", age: 33, email: "email@gmail.com" }; const { name: userName, email: mailAddress } = user;//In this case, the name property is mapped to the userName variable, and the email field is mapped to the mailAddress variable. console.log(userName);//Alexander console.log(mailAddress);//email@gmail.com
You can set default values for variables / constants, if the object suddenly does not have the corresponding properties:
const user = { name: "Alexander", age: 33, }; const { name = "Arnold", email: mailAddress = "email@gmail.com" } = user;//let's set the default properties console.log(name); //We will get Alexander, because our object has a name property console.log(mailAddress);//We will get email@gmail.com, this is the value we specified by default, because our object does not have such a property
If a variable/constant, when destructuring, is mapped to a property that represents a complex object, then after destructuring, this variable/constant will also represent a complex object:
let user = { name: "Alexander", age: 33, account: { login: "alexander", password: "12345" } }; const { account } = user;//the restructuring of the account property, in which another array is located, was carried out console.log(account.login);//alexander console.log(account.password);//12345
But if we want to get individual values from a nested complex object, as in the example above, the account object inside the user object, then we do not have to get this entire object – we can also provide for its properties individual variables/constants:
const user = { name: "Alexander", age: 33, account: { login: "alexander", password: "12345" } }; let { name, account: { login } } = user; console.log(name); //Alexander console.log(login); //alexander
Obtaining object properties using the rest operator
Rest operator or operator … allows you to get the remaining properties of the object that are not composed with variables/constants, into a separate variable/constant:
const user = { name: "Alexander", age: 33, phone: "+1112223333", email: "email@gmail.com" }; const { name, age, ...contacts } = user; console.log(name);// Alexander console.log(age);// 33 console.log(contacts); // {phone: "+1112223333", email: "email@gmail.com"}
In this case, we are decomposing the tom object into three constants: name, age, and contacts. The name and age constants are matched with the properties of the tom object by name. And the contacts constant gets all the remaining unmapped object/properties.