Home > Web Front-end > JS Tutorial > body text

JavaScript object destructuring usage analysis (detailed examples)

WBOY
Release: 2022-02-05 07:00:35
forward
3359 people have browsed it

This article brings you relevant knowledge about object destructuring usage analysis in JavaScript. I hope it will be helpful to you.

JavaScript object destructuring usage analysis (detailed examples)

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

Use destructuring to obtain values ​​from objects

The most basic use of object destructuring is to retrieve the value of a property key from an object.

For example, we define an object with two properties: name and age

const User = {
  name: '搞前端的半夏',
  age: 18
}
Copy after login
Copy after login

Traditionally, we will use dot (.) notation or subscript ([]) notation Method to retrieve a value from an object. The following code snippet shows an example of retrieving a value from an object using dot notation to retrieve the object's value id and name. employee

Before we wanted to get the value of a certain attribute in the object, we usually used . or [].

const name = User['name'];
const age = User.age;
Copy after login

Of course these two methods are no problem in the current situation, but when there are too many User attributes, we have to copy and paste constantly, resulting in a lot of repeated code.

With structure assignment, we can quickly get the value. For example we create a variable using the key name of the object 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 repeated code.

const { name, age } = User;
Copy after login

Use destructuring to get values ​​from nested objects

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

const User = {
  name: '搞前端的半夏',
  age: '18',
  contact:{
    phone:'110',
  }
}
Copy after login

If we use . to go back and forth with the value of phone, it will take two times.

const phone = User.contact.phone;
Copy after login

If we use destructuring assignment: the writing is as follows:

const  {contact:{phone}}=User
consosle.log(phone)  // 输出10.
Copy after login

Whether it is No matter how many levels of nesting there are, as long as you follow this writing method, you will definitely get the specific value.

Use object destructuring to define a new variable and default value

Default value

Of course we may encounter many extreme situations in the daily development process,

For example, the object passed from the backend may be missing some fields

const User = {
  name: '搞前端的半夏',
}
Copy after login

or the attribute has no specific value:

const User = {
  name: '搞前端的半夏',
  age: ''
}
Copy after login
Copy after login
Copy after login

When we use destructuring assignment: regardless of whether age exists If there are attributes, the age variable will be created.

const { name, age } = employee;
Copy after login

When User.age has no specific value, we can use

const { name, age=18 } = employee;
Copy after login

to give age a default value.

New variable

Hold on, wait. There’s more magic on display in the deconstruction section! How to create a completely new variable and assign a value calculated using the object's property value? 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} 今年 ${age} `} = User ;
console.log(detail); // 输出:搞前端的半夏 今年 18
Copy after login

Using JavaScript object destructuring aliases

In JavaScript object destructuring, you can name the destructuring variable alias. Very handy for reducing the chance of variable name conflicts.

const User = {
  name: '搞前端的半夏',
  age: ''
}
Copy after login
Copy after login
Copy after login

Suppose we want to use destructuring assignment to obtain the value of the age attribute, but the variable age is already in the code. At this time, we need to define an alias in the structure.

const { age: userAge } = User;
console.log(userAge); //搞前端的半夏
Copy after login

And if you use age, an error will be reported.

console.log(age);
Copy after login

Using object destructuring to handle dynamic name properties

We often handle API response data as JavaScript objects. These objects may contain dynamic data, so as a client we may not even know the property key names in advance.

const User = {
  name: '搞前端的半夏',
  age: ''
}
Copy after login
Copy after login
Copy after login

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

function getPropertyValue(key) {
    const { [key]: returnValue } = User;   
    return returnValue;
}
Copy after login
const contact = getPropertyValue('contact');
const name = getPropertyValue('name');
console.log(contact, name); // 空  搞前端的半夏
Copy after login

Destructuring objects in function parameters and return values

Destructuring assignment parameters and passing parameters

Use object destructuring to pass attribute values ​​as parameters to functions.

const User = {
  name: '搞前端的半夏',
  age: 18
}
Copy after login
Copy after login

name Now let's create a simple function that creates a message dept using the and attribute values ​​to log in to the browser console.

function consoleLogUser({name, age}) {
  console.log(`${name} 今年 ${age}`); 
}
Copy after login

Pass values ​​directly as function parameters and use them internally.

consoleLogUser(User); // 搞前端的半夏 今年 18
Copy after login

Destructuring function object return value

There is another usage of object destructuring function. If the function returns an object, you can destructure the value directly into a variable. Let's create a function that returns an object.

function getUser() {
  return {
    'name': '搞前端的半夏',
    'age': 18
  }
}
Copy after login
const { age } = getUser();
console.log(age); // 18
Copy after login

Using Object Destructuring in Loops

The last (but not least) usage we will discuss is loop destructuring. Let us consider a set of employee objects. We want to iterate through the array and want to use the property values ​​of each employee object.

const User= [
  { 
       'name': '爱分享的半夏',
    'age': 16
  },
  { 
      'name': '搞前端的半夏',
    'age': 18
  },
  { 
        'name': '敲代码的半夏',
    'age': 20
  }
];
Copy after login

You can use a for-of loop to iterate over the User object, and then use object destructuring assignment syntax to retrieve details.

for(let {name, age} of employees) {
  console.log(`${name} 今年${age}岁!!!`);
}
Copy after login

JavaScript object destructuring usage analysis (detailed examples)

Related recommendations: javascript learning tutorial

The above is the detailed content of JavaScript object destructuring usage analysis (detailed examples). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:juejin.im
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!