The release of ES6 (ES2015) provides JavaScript with a much easier and faster way to handle object properties. This mechanism is called Destructuring (also known as Destructuring assignment). But do you really know how to use it? Do you really know how to use deconstructed assignment in various scenarios?
Use deconstruction to get values from objects
The most basic use of object deconstruction is to retrieve the value of a property key from an object.
For example, we define an object that has two attributes: name and age
const User = {
name: 'Pinellia in the front'.age: 18
}
Copy the code
Traditionally, we would use point (.) Notation or subscript ([]) notation retrieves a value from an object. The following code snippet shows an example of retrieving a value from an object using dot notation to retrieve its value ID and name. employee
Before we wanted to get the value of an attribute in the object, the general result was to use. Or [].
const name = User['name'];
const age = User.age;
Copy the code
Of course, these two methods are fine in the current situation, but when the User has too many attributes, we have to copy and paste over and over again, resulting in a lot of repetitive code.
With structure assignment, we can get values quickly. For example, we use the key name of the object to create variables and assign the value of the object to the same key. This way, no matter how many attributes there are, we just assign the attribute name, which also reduces a lot of repetitive code.
const { name, age } = User;
Copy the code
Use deconstruction to get values from nested objects
In the above example, User is a simple single-layer object. We also encounter nested objects in daily development, so how to retrieve the value of the nested object using structural assignment? Let’s redefine the User object and add a contact property to the object, which contains the User’s phone.
const User = {
name: 'Pinellia in the front'.age: '18'.contact: {phone:'110',}}Copy the code
If we use… to go back and forth with the value of phone, it takes two.
const phone = User.contact.phone;
Copy the code
If destructuring assignment is used: it is written as follows:
const {contact:{phone}}=User
consosle.log(phone) / / output 10.
Copy the code
No matter how many layers of nesting, if you write it this way, you will get a specific value.
Use object deconstruction to define a new variable and its default value
The default value
Of course, in the course of daily development, we may encounter many extreme situations,
For example, objects passed from the back end may be missing some fields
const User = {
name: 'Pinellia in the front',}Copy the code
Or the attribute has no specific value:
Const User = {name: '', age: ''}Copy the code
When we use destruct assignment: the age variable is created regardless of whether an age attribute exists.
const { name, age } = employee;
Copy the code
When user.age is not specific, we can use it
const { name, age=18 } = employee;
Copy the code
Give age a default value.
A new variable
Hold on. Hold on. More magic on display in the deconstruction section! How do I create a brand new variable and assign a value computed using the value of an object property? Sound complicated? This is an example,
What should we do when we want to output the combined value of the User attribute?
const { name,age,detail = `${name}This year,${age} `} = User ;
console.log(detail); // Output: get the front end of pinellia 18 this year
Copy the code
Use JavaScript objects to deconstruct aliases
In JavaScript object destruction, you can name the destruct variable alias. Reducing the chance of variable name conflicts is handy.
const User = {
name: 'Pinellia in the front'.age: ' '
}
Copy the code
Suppose we want to get the value of the age attribute using destruct assignment, but the age variable is already in the code, we need to define the alias at structure time.
const { age: userAge } = User;
console.log(userAge); // Do pinellia
Copy the code
If age is used, an error is reported.
console.log(age);
Copy the code
. *
Use object deconstruction to handle dynamic name attributes
We often treat API response data as JavaScript objects. These objects may contain dynamic data, so as clients we may not even know the property key name in advance.
const User = {
name: 'Pinellia in the front'.age: ' '
}
Copy the code
When we pass the key as an argument, we can write a function that returns the value of the User object property. Here we use [] to accept the argument, and js will retrieve it from the object based on this key pair!
function getPropertyValue(key) {
const { [key]: returnValue } = User;
return returnValue;
}
Copy the code
const contact = getPropertyValue('contact');
const name = getPropertyValue('name');
console.log(contact, name); // Do pinellia
Copy the code
Deconstruct objects in function arguments and return values
Deconstruct assignment and parameter passing
Object deconstruction is used to pass attribute values as arguments to functions.
const User = {
name: 'Pinellia in the front'.age: 18
}
Copy the code
Name now lets us create a simple function that uses and property values to create a message DEPT to log in to the browser console.
function consoleLogUser({name, age}) {
console.log(`${name}This year,${age}`);
}
Copy the code
Pass values directly as function parameters and use them internally.
consoleLogUser(User); // Get the front end of pinellia this year 18
Copy the code
Destruct the return value of the function object
Object destructors can be used in another way. If the function returns an object, you can deconstruct the value directly into a variable. Let’s create a function that returns an object.
function getUser() {
return {
'name': 'Pinellia in the front'.'age': 18}}Copy the code
const { age } = getUser();
console.log(age); / / 18
Copy the code
Use object deconstruction in loops
The last (but not least) use we’ll discuss is circular deconstruction. Let’s consider a set of employee objects. We want to iterate through the array and want to use the attribute values of each employee object.
const User= [
{
'name': 'Pinellia who Loves to Share'.'age': 16
},
{
'name': 'Pinellia in the front'.'age': 18
},
{
'name': 'Coding pinellia'.'age': 20}];Copy the code
You can iterate over the User object using a for-of loop, and then retrieve the details using the object destruct assignment syntax.
for(let {name, age} of employees) {
console.log(`${name}This year,${age}Years old!!!!!! `);
}
Copy the code