The introduction

Objects and arrays are two of the most commonly used data structures in Javascript, and they have become a particularly important part of the Javascript language due to the popularity of the JSON data format. In coding, we often define many objects and arrays and then systematically extract relevant pieces of information from them. A new feature has been added to ES6 to simplify this task: deconstruction. Deconstruction is the process of breaking up data structures into smaller pieces.

Why deconstruction is necessary

Let’s consider a situation that most people might encounter when coding in Javascript.

Suppose that we have a student data and use an object to represent the scores of three subjects (mathematics, Chinese and English) in the student data, we display the information of students’ scores according to these data:

const student = { name:'jsPool', age:20, scores:{ math:95, chinese:98, English :93}} function console.log(' console.log '+ student.log); The console. The log (' math scores: + (student) scores) math | | 0)); The console. The log (' language result: '+ (student. Scores. Chinese | | 0)); The console. The log (' English: + (student) scores) English | | 0)); } showScore(student) copies the codeCopy the code

Using the code above, we’ll get the result we need. However, code written this way needs to have a few caveats. Because scores, the object we accessed, is nested in student, our access chain becomes longer, which means more input, which makes spelling errors more likely. Of course, this is not a big deal, but with deconstruction, we can do the same thing with a much more expressive and compact syntax.

Object destructuring assignment

The syntactic form of object deconstruction is to place an object literal to the left of an assignment operator, for example:

let details = { firstName:'Code', lastName:'Burst', age:22 } const {firstName,age} = details; console.log(firstName); // Code console.log(age); // copy the codeCopy the code

In this code, the value of details.firstname is stored in the variable firstName, and the value of details.age is stored in the variable age. This is the most basic form of object deconstruction.

Here’s a picture to illustrate the deconstruction process:

Variable assignment without the same name

In this example, we use the same variable name as the property name of the object, but we can also define variable names that are different from the property name:

const person = { name: 'jsPool', country: 'China' }; const {name:fullname,country:place} = person; console.log(fullname); // jsPool console.log(place); // China copies the codeCopy the code

Here, we create two local variables: fullname, place, and map fullName to name and place to country.

The default value

When using a destruct assignment expression, if the specified local variable name does not exist in the object, the local variable is assigned undefined, like this:

const person = { name: 'jsPool', country: 'China' }; let {age} = person; console.log(age); // undefined copies the codeCopy the code

This code defines an additional local variable, age, and then tries to assign it a value, but on the Person object, there is no property value for the property name, so it is assigned undefined as expected.

When the specified attribute does not exist, you can define a default value by adding an equal sign (=) and the corresponding default value after the attribute name:

const person = { name: 'jsPool', country: 'China', sexual:undefined }; let {age = 20,sexual:sex = 'male'} = person; console.log(age); // 20 console.log(sex); // male copies the codeCopy the code

In this example, the default value 20 is set for the variable age and male is set for the variable sex that is not of the same name. The default is valid only if the property does not exist on the object Person or if the property value is undefined.

Destruct assignment of nested objects

Deconstructing nested objects is still similar to the syntax of object literals, and you can take objects apart to get the information you want.

Looking at the example at the beginning of the article, we have a student data. In the student data, an object is used to represent the scores of three subjects (mathematics, Chinese and English), and we display the information of students’ scores according to these data. We can elegantly manipulate this by deconstructing assignment:

const student = { name:'jsPool', age:20, scores:{ math:95, chinese:98, english:93 } } function showScore(student){ const { name,scores:{ math = 0,chinese = 0, english = 0}} = student; Console. log(' student name :' + name); Console. log(' math :' + math); Console. log(' Chinese result :' + Chinese); Console. log(' English scores :' + English); } showScore(student) copies the codeCopy the code

Here, we define four local variables: name, Math, Chinese, and English. We also specify default values for the math, Chinese, and English variables, respectively.

Destruct assignment of arrays

Array deconstruction is much simpler than object deconstruction. It uses array literals and does all the deconstruction inside the array, rather than using the named properties of the object, as object literals do.

let list = [221,'Baker Street','London']; let [houseNo,street] = list; console.log(houseNo,street); // 221, Baker Street copy codeCopy the code

In the above code, we deconstruct the values of index 0 and index 1 from the array List and store them in the variables houseNo and Street, respectively.

In array deconstruction, it is also possible to omit elements and provide variable names only for the elements needed:

let list = [221,'Baker Street','London']; let [houseNo,,city] = list; console.log(houseNo,city); // 221, London copies the codeCopy the code

In this code, the elements of index 0 and index 2 are extracted from the array list using the destruct syntax. The comma before city is a placeholder for the elements in front of it.

Here’s a picture to illustrate the deconstruction process:

The default value

It is also possible to add a default value to any position in an array in a destruction-assignment expression. The default value is used when the specified position attribute does not exist or its value is undefined:

let list = [221,'Baker Street']; let [houseNo,street,city = 'BJ'] = list; console.log(houseNo,street,city); // 221, Baker Street, BJ copy codeCopy the code

In the above code, the array list has only two elements, and the variable city has no matching value, but a default value BJ, so the final output of city is not undefined, but the default value BJ.

Destruct assignment of nested arrays

Just like objects, nested arrays can be deconstructed. To take the deconstruction process to the next level, insert another array deconstruction pattern into the existing array deconstruction pattern:

let colors = [ 'red' , [ 'green' , 'yellow' ] , 'blue' ]; let [ firstColor , [ secondColor ] ] = colors; console.log(firstColor,secondColor); // red, green copies the codeCopy the code

In this example, we assign corresponding values to the variables firstColor and secondColor through a nested deconstruction of the array.

Indefinite elements

In the array, you can use… The syntax assigns the rest of the array to a specific variable, like this:

let colors = ['red','green','blue']; let [firstColor,...otherColors] = colors; console.log(firstColor); // red console.log(otherColors); // ['green','blue'] copies the codeCopy the code

In this example, the first element of the array colors is assigned to firstColor, and the other elements are assigned to the otherColors array, so the otherColors contains two elements: ‘green’ and ‘blue’.

Mixed deconstruction

You can use a mixture of object deconstruction and array deconstruction to build more complex expressions, so that you can extract the information you want from any data structure that is a mixture of objects and arrays.

Let node = {name:'foo', loc:{start:{line :1, column:1}}, range:[0,3]} let {loc:{start:{line}}, range:[startIndex] } = node; console.log(line); // 1 console.log(startIndex); // 0 Copies the codeCopy the code

When using hybrid deconstruction syntax, you can extract any information you want from node objects.

Mixed deconstruction is especially useful when extracting data from JSON, eliminating the need to walk through the entire deconstruction.

From: juejin. Cn/post / 684490…