ES6 Lesson #12 - Destructive object assignment

In the last lesson, we looked at how to assign arrays destructively, in this I will tell you how to assign objects destructively.

In curly brackets indicate the variables that must match the name in the object. We assign an object to these variables.

let person = {
   firstname: 'Valera',
   lastname: 'Isip'
}

let {firstname, lastname} = person;

console.log(firstname, lastname) // returns Valera Isip

But what if we need to name the variables differently? Its simply:

let person = {
   firstname: 'Valera',
   lastname: 'Isip'
}

let {firstname: variable1, lastname: variable2} = person;

console.log(variable1, variable2) 

We can also use default values ​​in the assignment.

let person = {
   firstname: 'Valera',
   lastname: 'Isip'
}

let {firstname: variable1, lastname: variable2, corvo = 115} = person;

console.log(variable1, variable2, corvo) // returns Valera Isip 115

The properties of the object are a string when attached, so we can use them in dynamics.

let person = {
   firstname: 'Valera'
}

let {['first' + 'name']: variable1} = person;

console.log(variable1) // returns Valera

If you have nesting in an object, you can use the following syntax:

let person = {
   firstname: 'Valera',
   social: {
     instagram: '@ValeraBietKoneyLopatoy'
   }
}

let {firstname: variable1, social: {instagram: var2}} = person;

console.log(variable1, var2) // returns Valera @ValeraBietKoneyLopatoy

Why i need it, and how i can use it? For example:

function post({url, timeout}) {
  console.log(url, timeout);
}

let post1 = post({url: 'https://google.com', timeout: 300});
// returns https://google.com 300

Tudu to to to toooo.... 😎