preface

As a front-end that often deals with data coming back, deconstruction is the syntactic sugar of ES6, like a dark wizard that makes it easy to deal with complex data assignments.

As defined in MDN, the destruct assignment syntax is a Javascript expression. By deconstructing assignments, attributes/values can be taken from objects/arrays and assigned to other variables.

Basic usage

Take a look at some code that illustrates the difference between taking variable values and using deconstructed assignments in ES5

	In the old days we would take an array or an object and it would look something like this
		let arr = [1.2];
		let a = arr[1];
		let b = arr[2];
		console.log(a, b); / / 1, 2

		let obj = {
			c: 3.d: 4
		}
		let c = obj.c;
		let d = obj.d;
		console.log(c, d) / / 3, 4


		// Now use simple deconstruction
		/ / array
		let [a, b] = [1.2];
		console.log(a, b); / / 1. 2
		/ / object
		let {
			c,
			d
		} = {
			c: 3.d: 4
		}
		console.log(c, d); / / 3 4
Copy the code

The above code is simple deconstruction. The left and right sides of the equal sign are written in the same format, and the corresponding values can be extracted. The writing time of the code is greatly shortened, making it more concise and easy to read. What is deconstruction assignment

classification

Deconstructive assignment can be broadly divided into the following categories according to personal understanding
  • An array of deconstruction
  • Object to deconstruct
  • Nested deconstruction
  • Parameters of deconstruction

An array of deconstruction

Destruct can assign values to arrays

Simple array deconstruction assignment:
// Now use simple array destructuring
let [a, b] = [1.2];
console.log(a, b); / / 1. 2
Copy the code
When you are not interested in some value in an array:

Here, you can use,(comma) as a placeholder to indicate that a position is occupied

let [a,,b,c] = [1.2.3.4.5];
console.log(a,b,c)
// Prints the result as
/ / 1 and 4

let [c,,,d,e] = [1.2.3.4]
console.log(c,d,e)
// Prints the result as
/ / 1, 4, undefined
Copy the code

As can be seen from the above example, the comma can be used as a placeholder, the order of the variable corresponds to the order of the array one by one, and when the retrieval cannot be automatically copied as undefined. For example, the value of E in this example is undefiend

You can also use the extension operator (…) To participate in deconstruction
let [a,...b] = [1.2.3.4]
console.log(a,... b);// Print here
/ / 1/2 and 4
Copy the code

Note: SyntaxError is raised if there is a comma to the right of the remaining element, because the remaining element must be the last element in the array

var [a, ...b,] = [1.2.3];
// SyntaxError: rest element may not have a trailing comma
Copy the code
Deconstructing defaults

To prevent extracting a undefined from the array, we can also assign a default value to the deconstructed variable, and use the default value if the variable does not match

Let [a,b=1] = [1] //Copy the code

Object to deconstruct

In addition to arrays, objects can also be deconstructed, so let’s take a look

Simple object deconstruction assignment
1 / / examples
let {a,b} = {a:1.b:2}
// the value of b is 1 and b is 2
Copy the code
Renaming variables

Sometimes we take the value from the object, and it’s not just the same, we might have to rename it, and then deconstruction can do that as well.

The code in example 1 is essentially equivalent to

let {a:a.b:b} = {a:1.b:2}
Copy the code

The left side of the ":" is the name of the new variable, and the left side is used to match the position. In example 1, it is shorthand. For example, this feature allows us to extract variables whose names are different from those of the property in the object

let {a:r,b:f} = {a:1.b:2}
// Print the result:
//r = 1 and f = 2
Copy the code
The default value

Just like array deconstruction, the default values can also be set to avoid extracting undefiend variables

let {a=1,b} = {b:2}
// The default value of a and b is 1 and 2 respectively
Copy the code
You want a default value and you want to rename it

So we could write it like this

let {a:e,c:d=3} = {a:2}
// The value of e is 2, and the default value of d is 3

Copy the code

Function argument deconstruction

The traditional way, without deconstruction:
let obj = {
   c:10.d:11
}
function test(obj){
  return obj.c+obj.d
}		
Copy the code

In traditional function parameter passing, if we have more than one parameter, it is common to use one object to hold all the parameters for simplicity. Its obj argument is an object type; But we don’t know this just by looking at the declaration part of the function, which can cause inconvenience to the user: the user can’t be sure that the third argument is an object type and what attributes are needed in that object. The above problems can be solved by using deconstruction parameters

When using destruct parameters:

The following example uses a destruct parameter to deal with this problem. As you can see, what fields are required for the parameter to be clearly visible in the function declaration section

function test({c,d}){
	/ / the function body
}
/ / call
test({c:10.d:11})
Copy the code

Note: Deconstructing parameters cannot pass values The js code will report an error when we do not pass a value to the deconstruction parameter. To avoid this problem we set the default value to the deconstruction parameter as follows:

Set default values for the deconstruction parameters

When we do not use the deconstruction parameter, set the default value like this

let obj = {
	c:10.d:11
}
function test(obj){
	let tem = obj.c || null;
	let tem1 = obj.d || null;
	return obj.c+obj.d
}
Copy the code

When we use deconstruction, it’s written like this

let obj = {
	c:10.d:11
}
function test({c,d}={}){
	/ / the function body
}
Copy the code
Use deconstructed assignment to deal with this multi-parameter problem

See the example in the figure below

let obj = {
	c:10.d:11
}
function test({c,d} = {}){
	/ / the function body
}
test()
Copy the code

In the example above, no error will be reported if no parameter is passed after using the default value

Assign a value to each item of the deconstruction parameter

We can also assign values to each of the deconstructed parameters

let obj = {
	c:10.d:11
}
function test({c=10,d=11} = {}){
	/ / the function body
}
test()
Copy the code

As in the example above, use the = sign to assign the default value

Nested deconstruction

Simple deconstruction is as simple as the above, but the data returned by the background is often very complex, let’s take a background JSON as an example, how to deal with complex data

let res = {
	code: 200.data: [{name: "Juejin".info: '1'.children: {
				msg: 'subdata'}}}]/ / deconstruction
let { 
	  code,
	  data:[
		{ 
		  name,
		  info, 
		  children:{msg} 
		}
	  ]
} = res
console.log(code, name, info, msg)
Copy the code

The basic rule is to keep the left and right sides of the equal sign the same

The function prints:Note that on the third line after the destruct comment in the code above, we initialize the variables name and info, not data. Data is just the parent of name and info. The same is true for children and MSG in the following sections

The syntax for destructuring nested objects is to locate the outermost variable of the original object, all the way to the desired level, separated by a colon:, with the variable to the right of the colon

Tip: The various basic uses of deconstruction, setting defaults, and renaming can also be used for nesting