Deconstruction: make data access more convenient!

preface

Original intention: Recently reading In depth understanding Es6 I haven't studied Es6 grammar thoroughly before, but I'll study it again when I'm not busy, sort out my notes and share them with you. Don't spray it if you don't like it.

Suitable for people: front-end primary development, big guys bypass.

Content structure: basic grammar - > pros and cons of grammar - > application scenario

Why use deconstruction

In Es5, we usually want to get specific data from objects or array objects. Let's look at the following example

let person = {
    name: "Frogman",
    age: 24
}

let name = person.name
let age = person.age

In the above example, we can see that we get the name and age attributes from the person object and assign them to the newly declared variables name and age. It's no problem to declare two variables in this way. What if there are more in the future.

Therefore, Es6 provides the deconstruction function for objects and arrays, which makes the process of breaking up the data structure easier, and the required information can be obtained from the smaller part after breaking up. Let's have a look

Object deconstruction

let person = {
    name: "Frogman",
    age: 24
}
let { name, age } = person
console.log(name) // Frogman
console.log(age) // 24

In the above example, person The value of name is assigned to the name variable, person The value of age is assigned to the age variable. It's just that here is the abbreviation syntax of objects. If you don't understand the new features of objects, please see my last article What properties does Es6 object extend

Don't forget the initialization value

If var, let and const are used to declare deconstruction, the value must be initialized, that is, the variable on the right. Let's take an example

var { name, age }; // Syntax throw error
let { name, age }; // Syntax throw error
const { name, age }; // Syntax throw error

In the above example, we can see that if there is a declaration to deconstruct the assignment and does not initialize the value, an error will be thrown. If it is not used for deconstruction, the variables declared by var and let may not need the initialization value, but the variables declared by const must have the initialization value, otherwise an error will be thrown. If you don't understand the difference between var, let and const, read my article The difference between var, let and const

Note: if the value on the right side of the deconstruction assignment is null or undefined, an error will be thrown. Remember.

Destructuring assignment

In the above, we have finished deconstruction, so what is deconstruction assignment. That is, we also use deconstruction syntax when assigning values to variables. Look at the following example

let name = "Xiao Wang"
let age = 18
let person = {
    name: "Frogman",
    age: 24
};
// Assign values to variables using deconstruction assignment
({ name, age } = person);
console.log(name) // Frogman
console.log(age) // 24

In the above example, we first define the name and age variables and initialize the values, and then read and re assign the name and age variables from the person object through the deconstructed assignment method. Note that the deconstruction assignment statement must be wrapped with a pair of parentheses. The JavaScript engine will treat the curly braces as a code block, and the syntax stipulates that the code block cannot appear on the left side of the assignment statement. After wrapping with parentheses, the code block can be converted into an expression, so that the deconstruction assignment can be realized.

Next, we use deconstruction assignment expressions in function parameters

let name = "Xiao Wang"
let age = 18
let person = {
    name: "Frogman",
    age: 24
};
function getObj(data) {
    console.log(data == person) // true, where the data is person, and the value of the expression is = the value on the right
}
getObj({ name, age } = person)
console.log(name) // Frogman
console.log(age) // 24

In the above example, when calling the getObj function, a deconstructive assignment expression is introduced. Because the value of the JavaScript expression is the value on the right side, the parameter object in the function is the person object, and the name and age variables are also reassigned.

When using deconstruction assignment, if the specified variable name does not exist in the object, the variable is undefined. Let's look at the following example

let person = {
    name: "Frogman",
    age: 24
}
let { name, age, sex} = person;
console.log(name, age, sex) // Frogman 24 undefined

In the above example, there is a sex variable in the deconstruction assignment expression, but obviously the sex attribute does not exist in the object. At this time, the sex variable will be assigned to undefined.

When the specified attribute does not exist, we can set a default value, which is the same as the default value of function parameters. Let's look at the following example

let person = {
    name: "Frogman",
    age: 24
}
let { name, age, sex = "male" } = person;
console.log(name, age, sex) // Frogman 24 male

In the above example, set the default value for sex. The default value will take effect only when the attribute is not on the person object or the attribute is undefined. This is the same as the default value of the function. If you don't understand, you can see my article Do you really understand the function features in ES6.

Deconstruction assignment alias

In the above code, we deconstruct expressions with the same variables and attribute names. Sometimes we deconstruct expressions that do not want to be the same as this attribute name. What should we do? The deconstructed expressions agree to support aliasing. Let's look at the following example

let person = {
    name: "Frogman",
    age: 24
}
let { name: userName, age: userAge } = person
console.log(userName) // Frogman
console.log(userAge) // 24

In the above example, the above deconstruction expression stores the name attribute in userName and the age attribute in userAge, so the name and age cannot be accessed at this time because they are no longer variables.

Default parameters are also supported for deconstruction assignment aliases

let person = {
    name: "Frogman",
    age: undefined
}
let { name: userName, age: userAge = 24 } = person
console.log(userName) // Frogman
console.log(userAge) // 24

I won't say much here. It's the same as the default parameters mentioned above.

Object multi-layer nested deconstruction

Deconstruction assignment also supports multi-layer nesting. The syntax is the same as the literal quantity of the object mentioned above, which can be split and deconstructed in more detail. Let's look at the following example

let person = {
    name: "Frogman",
    age: 24,
    hobby: {
    	name: "Write code"
    }
}
let { hobby: { name: code = "code" } } = person
console.log(code) // Write code

In the above example, you can see that the above multi-level deconstruction syntax is the same as that of ordinary deconstruction, except that a layer of {} curly braces is nested. We have deconstructed the hobby attribute above, and then continue to further deconstruct the name attribute and give it a default value, and then we give it an alias variable code.

Object deconstruction minefield

When using multi-layer nested deconstruction, it should be noted that you may inadvertently create an invalid expression, which is to deconstruct empty curly braces, but this syntax is also legal, and you won't do anything or report an error. Let's take a look.

let person = {
    name: "Frogman",
    age: 24,
    hobby: {
    	name: "Write code"
    }
}
let { hobby: {} } = person

In the above statement, you can see that there is a {} bracket on the right side of the deep deconstruction hobby attribute, but no variable is declared. This statement is also reasonable and will not report an error. The official answer: this grammar may be abandoned in the future. We just need to know not to write it like this.

Array deconstruction

Array deconstruction syntax is similar to object deconstruction syntax, but array deconstruction is deconstructed with [] literal syntax. See the following example.

let colors = ["red", "blue", "green"]
let [ red, blue ] = colors
console.log(red, blue) // red blue

The biggest difference between array deconstruction and object deconstruction is that object deconstruction is disordered while array deconstruction is orderly. Let's take a look at the following example.

let colors = ["red", "blue", "green"];
let [ blue ] = colors
console.log(blue) // red

let ObjColors = {
    red: "red",
    blue: "blue",
    green: "green"
}
let { blue } = objColors
console.log(blue) // blue

In the above example, we can see that the blue variable of array deconstruction is the red value, so the array deconstruction is based on the position. A position corresponds to a value. We can't get the value in the object directly if there is a value in the object like the literal value of the object. We don't need to follow the order. Array deconstruction requires sequential deconstruction.

If we only want to get the second value of the array, we can directly ignore the variable of the first value and just write a placeholder. Let's look at the following example

let colors = ["red", "blue", "green"]
let [ , blue ] = colors
console.log(blue) // blue

In the above example, only the second value is obtained, so deconstruct the array. The first value only occupies the bit and does not declare the variable, and then write the blue variable, so that only the second value can be obtained.

Array deconstruction is the same as object deconstruction. The array deconstruction declared by var, let and const must be initialized, otherwise an error will be thrown. As mentioned above when deconstructing the opposite side, remember.

Array deconstruction default

The default value of array deconstruction is the same as that of object deconstruction. As long as there is no value in the array or the value is set to undefined, the default value will take effect.

let person = ["Frogman", 24]
let [ name, age, sex = "male" ] = person
console.log(name, age, sex) // Frogman 24 male

Multi layer nested deconstruction of arrays

Array multi-layer nested deconstruction is similar to object multi-layer nested deconstruction, but the syntax is different. Array is deconstructed in order using []. Let's look at an example

let person = ["Frogman", 24, ["Write code", "Flirt with younger sister", "badminton"]]
let [ name, age, [firstHobby] ] = person
console.log(name, age, firstHobby) // Frog 24 write code

In the above example, we can see that when multi-layer deconstruction, we use [] square brackets to go deep layer by layer and extract the data we want layer by layer.

The syntax of array deconstruction and object deconstruction are similar. Just note that array deconstruction uses [], object deconstruction uses {}, and their minefields are the same. If I use deconstruction, I must initialize the value on the right, otherwise an error will be reported.

Mixed deconstruction

After the above, all the above are about single object deconstruction. Now we can do some mixed deconstruction, which requires both data deconstruction and object deconstruction. Look at the following example

let person = {
    name: "Frogman",
    age: 24,
    sex: "male",
    hobby: ["Write code", "Flirt with younger sister", "badminton"]
}
let { name, sex, hobby: [, , lastHobby] } = person
console.log(name, sex, lastHobby) // Breastman male badminton

In the above example, person is an object that defines personal information. Then, in the following deconstruction, object deconstruction and array deconstruction are used. Then we know that array deconstruction can only be deconstructed according to location, so we use array placeholders to obtain the value of the last array.

So what is the use of so much grammar? What kind of scenario is used? Let's take a look at these syntax application scenarios

Application scenario

Object deconstruction

Usually in Es5, for example, we need to do a personal information display function. We first write a function and then pass an object. In this function, we need to declare and assign a bunch of variables, and these values are taken from the object passed in. Let's look at the following example

function informationFn(data) {
    let name = data.name;
    let age = data.age;
    let sex = data.sex;
    let email = data.email;
    let phone = typeof data.phone != "undefined" ? data.phone : "Not yet";
}
let person = {
    name: "Frogman",
    age: 24,
    sex: "male",
    email: "xxxxxx@163.com",
    phone: undefined
}
informationFn(person)

In the above example, we can see that although there is no problem with the code, there are too many codes, resulting in code redundancy. Now we are using Es6 syntax to realize the above functions.

function informationFn({ name, age, sex, email, phone = "Not yet" }) {
    console.log(name, age, sex, email, phone)
}
let person = {
    name: "Frogman",
    age: 24,
    sex: "male",
    email: "xxxxxx@163.com",
    phone: undefined
}
informationFn(person)

In the above example, we use Es6 syntax to deconstruct objects and deconstruct default values. We can see that the code is very concise.

Array deconstruction and assignment

In Es5, if we want to exchange values between two variables, we have to rely on the first variable.

let a = 1;
let b = 2;
let temp;
temp = a;
a = b;
b = temp;
console.log(a, b) // 2 1

However, in Es6, there is an array deconstruction assignment, which is completely unnecessary. Let's see how to implement it.

let a = 1;
let b = 2;
[ a, b ] = [b, a]
console.log(a, b)

In the above example, the expression on the right side of the deconstruction assignment is a temporary array. It will first calculate the right array, and finally assign the right array to the previous array variable.

thank

Thank you for opening this article at the midpoint of your busy schedule. I hope it can be helpful to you. If you have any questions, you are welcome to make corrections.

If you think it's OK, give it a compliment.

If you are interested, you can also add my personal vx for communication Contact me

Tags: Javascript red hobby

Posted by calmchess on Sat, 16 Apr 2022 03:12:00 +0930