Analysis of JavaScript object deconstruction usage

The release of ES6 (ES2015) provides JavaScript with a more convenient and fast way to deal with the properties of objects. This mechanism is called Destructuring (also known as deconstruction assignment). But can you really use it? Do you really understand the usage of deconstruction assignment in various scenarios?

Get values from objects using deconstruction

The most basic usage of object deconstruction is to retrieve the value of attribute key from object.
For example, we define an object that has two properties: name and age

const User = {
  name: 'Front end',
  age: 18
}

Traditionally, we will use point (.) The notation or subscript ([]) notation retrieves a value from an object. The following code snippet shows an example of retrieving an object's value id and name from an object using a dot symbol. Before employee, we want to get the value of a property in the object. The general production is to use Or [].

const name = User['name'];
const age = User.age;

Of course, these two methods have no problem in the current situation, but when there are many User attributes, we keep copying and pasting, resulting in a lot of duplicate code.

With structure assignment, we can get the value quickly. For example, we use the key name of the object to create a variable and assign the value of the object to the same key. In this way, no matter how many attributes there are, we only need to assign the attribute name, which also reduces a lot of duplicate code.

const { name, age } = User;

Get values from nested objects using deconstruction

In the above example, User is just a simple single-layer object, and we will encounter nested objects in our daily development. How can we retrieve the values in nested objects using structure assignment. Next, we redefine the User object and add a contact attribute to the object, which contains the User's phone.

const User = {
  name: 'Front end',
  age: '18',
  contact:{
    phone:'110',
  }
}

If we use it At that time, it takes two times to return to the phone value

const phone = User.contact.phone;

If deconstruction assignment is used, it is written as follows:

const  {contact:{phone}}=User
consosle.log(phone)  // Output 10

No matter how many layers of nesting, as long as you write in this way, you will get specific values.
Use object deconstruction to define a new variable and default values

Default value

Of course, we may encounter many extreme situations in the process of daily development,
For example, some fields may be missing for objects passed from the back end

const User = {
  name: 'Front end',
}

Or the attribute has no specific value:

const User = {
  name: 'Front end',
  age: ''
}

When we use deconstruction assignment: the age variable will be created whether the age attribute exists or not.

const { name, age } = employee;

When user If age is not specific, we can use it

const { name, age=18 } = employee;

Give age a default value.

New variable

Hold on, wait a minute. Deconstruction part has more magic display! How to create a new variable and assign a value calculated using the object attribute value? Sounds 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: engaged in front-end this year 18 

Deconstructing aliases using JavaScript objects

In JavaScript object deconstruction, you can name the deconstruction variable alias. It is very convenient to reduce the chance of variable name conflict.

const User = {
  name: 'Front end',
  age: ''
}

Suppose we want to use deconstruction assignment to obtain the value of the age attribute, but the variable age has been added in the code. At this time, we need to define an alias in the structure.

const { age: userAge } = User;
console.log(userAge); //Front end

If age is used, an error will be reported.
console.log(age);

. *
Handling dynamic name attributes using object deconstruction

We often treat API response data as JavaScript objects. These objects may contain dynamic data, so as clients, we may not even know the attribute key name in advance.

const User = {
  name: 'Front end summer',
  age: ''
}

When we pass the key as a parameter, we can write a function that returns the value of the User object property. Here we use [], to accept parameters. js will retrieve from the object according to this key pair!

function getPropertyValue(key) {
    const { [key]: returnValue } = User;   
    return returnValue;
}
const contact = getPropertyValue('contact');
const name = getPropertyValue('name');

console.log(contact, name); // Empty front-end

Deconstruct objects in function parameters and return values

Deconstruction assignment parameters

Use object deconstruction to pass attribute values to functions as parameters.

const User = {
  name: 'Front end',
  age: 18
}

name now let's create a simple function that uses and attribute values to create a message dept to log in to the browser console.

function consoleLogUser({name, age}) {
  console.log(`${name} this year ${age}`); 
}

Pass values directly as function parameters and use them internally.

consoleLogUser(User); // The front-end Pinellia ternata is 18 this year

Return value of deconstruction function object

There is another use of object deconstruction functions. 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': 'Front end',
    'age': 18
  }
}
const { age } = getUser();
console.log(age); // 18

Using object deconstruction in a loop

The last (but not least) usage we will discuss is loop deconstruction. Let's consider a group of employees. We want to traverse the array and want to use the property values of each employee object.

const User= [
  { 
       'name': 'Love sharing',
            'age': 16
  },
  { 
      'name': 'Front end',
            'age': 18
  },
  { 
        'name': 'Knock code',
            'age': 20
  }
];

You can use the for of loop to traverse the User object, and then use the object deconstruction assignment syntax to retrieve the details.

for(let {name, age} of employees) {
  console.log(`${name} this year ${age}year!!!`);
}

key word: Front end training

Keywords: Javascript

Added by nbaxley on Mon, 07 Feb 2022 04:43:32 +0200