Destructuring is a concept that decomposes one of the data types and assigns its individual attributes to variables. It was introduced in the article "5 Common Scenarios and Examples of JavaScript Destructuring Assignment". Let’s review it today. one time.
const fullName = { firstName: "Quintion", lastName: "Tang", }; const { firstName, lastName } = fullName; // 解构语法 console.log(firstName); // Quintion console.log(lastName); // Tang
As seen in the above code snippet, in the destructuring syntax, the firstName
object property is decomposed and assigned to the expression left Variables defined on the side. In the above scenario, the object's property names should match the variables defined in the expression on the left. If you define other variable names, you will not get the desired value, such as:
const fullName = { firstName: "Quintion", lastName: "Tang", }; const { firstName, trueName } = fullName; // 解构语法 console.log(firstName); // Quintion console.log(trueName); // undefined
Since there is no attribute trueName
in fullName
, it is initialized to undefined
.
If you need to assign object attributes to variable names with inconsistent attribute names, you can implement it with the following code:
const fullName = { firstName: "Quintion", lastName: "Tang", }; const { firstName: trueName, lastName } = fullName; // 解构语法 console.log(trueName); // Quintion console.log(lastName); // Tang
As you can see in the above code, there is no destructuring of specific attributes in the object. Generally, the value is assigned to undefined
. If you do not want it to be undefined
, you can set a default value for it, as follows :
const fullName = { firstName: "Quintion", lastName: "Tang", }; const { firstName: trueName, lastName, age = 18 } = fullName; // 解构语法 console.log(trueName); // Quintion console.log(lastName); // Tang console.log(age); // 18
Let’s take a look at the results under the age
attribute:
const fullName = { firstName: "Quintion", lastName: "Tang", age: 30, }; const { firstName: trueName, lastName, age = 18 } = fullName; // 解构语法 console.log(trueName); // Quintion console.log(lastName); // Tang console.log(age); // 30
If you want to deconstruct an attribute from an object, The remaining attribute structure is another variable, as follows:
const fullName = { firstName: "Quintion", lastName: "Tang", age: 30, }; const { age, ...username } = fullName; // 解构语法 console.log(username); // { firstName: 'Quintion', lastName: 'Tang' } console.log(age); // 30
In the above code snippet, the username
attribute is assigned to a variable and uses rest## The # operator (
...) assigns the remaining properties of the variable to a separate object.
JavaScript Video Tutorial"
The above is the detailed content of Let's take a look at object destructuring in JavaScript. For more information, please follow other related articles on the PHP Chinese website!