Es6 provides a nice feature called deconstructed assignment of variables. This makes it easy to extract data from arrays and objects and assign them to variables. This is very necessary. Let’s take a look at how we extracted data from arrays before this new feature was released. As follows:

let nums = [1.2.3.4.5];
let num1 = nums[0];
let num2 = nums[1];

console.log(num1); // logs 1
console.log(num2); // logs 2
Copy the code

To extract data from the NUMS array, we repeat the same code many times. Es6’s deconstruction assignment will make this operation much easier and easier to understand.

Destruct assignment of arrays

Values from an array and assigns variables to their positions. As follows:

 let [num1,num2,num3] = [1.2.3];
 console.log({num1},{num2},{num3})
Copy the code

Pattern match assignment

This is “pattern matching,” and as long as the pattern on both sides of the equal sign is the same, the variable on the left will be assigned the corresponding value.

let [num_s,nums,num_e] = [1[2.3.4].5];
console.log(num_s) // logs 1
console.log(nums) / / logs / 2 and 4
console.log(num_e) // logs 5
Copy the code

Skip elements with commas

let [num1,,,num4] = [1.2.3.4];
console.log(num1) // logs 1
console.log(num4) // logs 4

let [,num2,,num4] = [1.2.3.4];
console.log(num2) // logs 2
console.log(num4) // logs 4
Copy the code

Look at the array to the left of the variable assignment. Notice there’s not just one comma, there’s three. Comma delimiters are used to skip values in an array. So if you want to skip an item in the array, just use a comma.

Assignment to the rest of the array

What if we want to assign some elements of the array to variables, but store the rest of the array as an array to assign to the specified variable? In this case, we can do this:

let [num1,...nums] = [1.2.3.4];
console.log(num1) // logs 1
console.log(nums) / / logs / 2 and 4
Copy the code

In this way, you can easily assign the remaining elements to a specified variable.

Deconstruct failure, assignundefined

let [num1] = [];
let [num2, num3] = [1];
console.log(num1) // logs undefined
console.log(num3) // logs undefined
Copy the code

Num1 = num3; num1 = num3; num1 = num1; num3 = num3; The variable num2 is assigned a value of 2 according to the pattern matching principle.

Function destruct assignment

Destructuring assignments can also extract data from an array returned by a function. Suppose we have a function that returns an array, as in the following example:

function getLists() {
    let lists = [1.2.3.4.5]
    return lists;
}
let [num1,...nums] = getLists();

console.log(num1); // logs 1
console.log(nums); / / logs, 5-tetrafluorobenzoic [2]
Copy the code

Use default values

Array destruct assignment can set variables to default values in case the value extracted from the array is undefined (in case destruct fails)

let [name = "No name yet.",sex = "Female"] = ["April"];

console.log(name); // "April"
console.log(sex); / / "female"
Copy the code

The default value of the variable name in the code is “no name yet”, but according to the principle of left-right pattern matching,name is assigned to “April”, since the variable sex does not match, so its value is still the default value of “female”.

Note 1: ES6 internally uses the strict equality operator (===) to determine whether a position has a value. Therefore, the default value is valid only if an array member is strictly equal to undefined.

let [num1 = 1] = [undefined];
console.log(num1) // logs 1

let [num2 = 2] = [null];
console.log(num2) // logs null
Copy the code

In the code, because null does not exactly equal undefined, the default value does not take effect. So null is printed

Note # 2: If the default value is a function, the function will be lazy, executing the function only when it is needed.

 function getLists(){
    let lists = [1.2.3.4.5]
    return lists; 
 }
let [lists = getLists()] = [1];
console.log(lists) // logs 1
GetLists () does not execute because lists can match to the value.

 function getLists(){
    let lists = [1.2.3.4.5]
    return lists; 
 }
let [lists = getLists()] = [];
console.log(lists) / / logs [1, 2, 3, 4, 5]
// Since variable lists cannot match the value, getLists() is executed. So return data [1,2,3,4,5]
Copy the code

Note 3: The default value can refer to another variable in the deconstructed assignment, but that variable must already be declared.

let [x = 1, y = x] = [];     // logs x=1; y=1
let [x = 1, y = x] = [2];    // logs x=2; y=2
let [x = 1, y = x] = [1.2]; // logs x=1; y=2
let [x = y, y = 1] = [];     //logs this is an error because y has not been declared when x uses y as the default value.
Copy the code

Switching variable

let num1 = 1;
let num2 = 2;

[num1,num2] = [num2,num1];

console.log({num1}); // logs 2
console.log({num2}); // logs 1
Copy the code

Object destructuring assignment

Why t use deconstruction of objects?

 let profiles = {
    name:'April'.nickname:"Twenty-seven minutes".sign:"Don't rejoice in things, don't grieve over yourself."
 }
           
let name = profiles.name;
let nickname = profiles.nickname;
let sign = profiles.sign;

console.log({name}) // "April"
console.log({nickname})// "27 minutes"
console.log({sign}) // "Do not rejoice in things, do not grieve over yourself."
Copy the code

Suppose we want to get data from the object Profiles and assign it to a new variable. You have to evaluate and assign over and over again. The code is verbose and not maintainable. With object deconstruction assignment, this problem does not exist.

Assign to the same attribute name

The destruction-assignment variable of the object must have the same name as the attribute to get the correct value. As follows:

let profiles = {
     name:'April'.nickname:"Twenty-seven minutes".sign:"Don't rejoice in things, don't grieve over yourself."
}
let {name,nickname,sign} = profiles;

console.log({name})    // logs "April"
console.log({nickname})// logs "27 minutes"
console.log({sign})    // Logs "Don't like things, don't like yourself."
Copy the code

Deconstruct failure, assignundefined

let profiles = {
    name:'April'.nickname:"Twenty-seven minutes".sign:"Don't rejoice in things, don't grieve over yourself."
}
let {name,sex} = profiles;

console.log(name) // logs "April"
console.log(sex) // logs undefined
Copy the code

In the above code, because the Profiles object has no sex attribute, the variable sex cannot take a value, so it is assigned undefined.

Declare variables before assignment

In a deconstructive assignment of an object, variables can be declared before the assignment. As follows:

let profiles = {
    name:'April'.nickname:"Twenty-seven minutes".sign:"Don't rejoice in things, don't grieve over yourself."
}
let name,nickname,sign;
{name,nickname,sign} = profiles;

console.log(name) // logs Error : "Unexpected token ="
Copy the code

Hey ~ error! Why??

Cause: Forgot to write () around {}.

Note 1: When deconstructing an assignment using an undeclared object literal, the assignment statement of () must be used. Because the JavaScript engine interprets {name,nickname,sign} as a code block, not as an object literal.

Note 2: When using this syntax, the previous line of code must start with; End, otherwise it will be treated as a function that executes the previous line of code.

It’s this weird syntax :({} = “);

The correct approach is as follows:

let profiles = {
    name:'April'.nickname:"Twenty-seven minutes".sign:"Don't rejoice in things, don't grieve over yourself."
}
let name,nickname,sign;
({name,nickname,sign} = profiles);

console.log({name},{nickname},{sign})
// logs {name: "April"} {nickname: "27 "} {sign:" not with things, not with your own." }
Copy the code

Use the new variable name

What if we want to replace the object’s property name with a new variable name? The code is as follows:

let profiles = {
    name:"April".age:"27"
}
let {name:userName,age:userAge} = profiles;

console.log(userName) // logs "April"
console.log(userAge) // logs "27"
Copy the code

Let {name:name,age:age} = {name:”April”,age:”27″} In other words, the internal mechanism of deconstructive assignment of an object is to find the property of the same name and then assign it to the corresponding variable. It is the latter, not the former, that is really assigned.

In the above code, name is the matching pattern and userName is the variable. The variable userName is actually assigned, not the schema name.

Use default values

It is important to note that the default value is valid only if the attribute value of the object is exactly equal to undefined.

let staff = {name: "April".country: "China".job: "Developer"};
let {name = "No name yet.", age = "No age yet"} = staff;

console.log({name}); // logs "April"
console.log({age}); // logs "no age yet"
Copy the code

The default value of the variable name in the code is “no name yet”, but the staff object has a field of name, so April is assigned, and the staff object does not have an age, so it is assigned “no age yet”, taking its own default value.

Compute attribute name

Evaluating attribute names is another object feature that also applies to destructuring assignment of objects. You can specify the name of an attribute through an expression and put it in [] as follows:

let staff = {name: "April".country: "China".job: "Developer"};
let prop = "name";
let {[prop]: name} = staff;

console.log({name}); // logs "April"
Copy the code

Assignment to the rest of the object

A deconstruction operation can also be carried into a deconstruction assignment to retrieve unassigned key-value pairs that are placed in a new object. As follows:

let staff = {name: "April".country: "China".job: "Developer".nickname:"Twenty-seven minutes"};
let{country,... infos} = staff;console.log(country) //logs "China"
console.log(infos) // logs {name: "April", job: "Developer", nickname: "27 "}
Copy the code

Destruct assignment of nested objects

let staffs = {
    group1:[ { id:"007".name:"April"}}]let {group1,group1:[{id,name}]} = staffs;

console.log(group1) // logs [{ id:"007", name:"April"}]
console.log(id) // logs "007"
console.log(name) // logs "April"
Copy the code

Notice that group1 in the code is a schema, not a variable. If you want to assign group1 as a variable, define it before assigning it.

The last

Array and object deconstruction assignment, this article summarizes so much. Deficiencies, hope to point out.