ES6 object destructuring usage

Get into the habit of writing together! This is the 8th day of my participation in the "Nuggets Daily New Plan · April Update Challenge", click to view the details of the event .

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

Get value from object using destructuring

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
}
复制代码

Traditionally, we would retrieve values ​​from objects using dot (.) notation or subscript ([]) notation. The following code snippet shows an example of retrieving an object's value idand nameretrieving values ​​from an object using dot notation.employee

Before we wanted to get the value of a property in an object, it was common to use .or [].

const name = User['name'];
const age = User.age;
复制代码

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

With structure assignment, we can quickly get the value. 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 properties there are, we only need to assign the property name, which also reduces a lot of repetitive code.

const { name, age } = User;
复制代码

Get values ​​from nested objects using destructuring

In the above example, User is just a simple single-layer object, and we also encounter nested objects in daily development, so using structure assignment, how do we retrieve the values ​​in the nested objects. Next, we redefine the User object and add a contact property to this object, which contains the User's phone. .

const User = {
  name: '搞前端的半夏',
  age: '18',
  contact:{
    phone:'110',
  }
}
复制代码

If we use .the value of the phone back and forth at that time, it takes twice.

const phone = User.contact.phone;
复制代码

If destructuring assignment is used: it is written as follows:

const  {contact:{phone}}=User
consosle.log(phone)  // 输出10.
复制代码

No matter how many levels of nesting, as long as you follow this writing method, you will definitely get a specific value.

Use object destructuring to define a new variable with a default value

Defaults

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

例如后端传过来的对象,可能会缺失某些字段

const User = {
  name: '搞前端的半夏',
}
复制代码

或者属性没有具体的值:

const User = {
  name: '搞前端的半夏',
  age: ''
}
复制代码

当我们使用解构赋值的话:无论是否存在age属性的话,都会创建age变量。

const { name, age } = employee;
复制代码

当User.age没有具体值得话,我们则可以使用

const { name, age=18 } = employee;
复制代码

给age一个默认值。

新变量

坚持,稍等。解构部分有更多的魔力展示!如何创建一个全新的变量并分配一个使用对象属性值计算的值?听起来很复杂?这是一个例子,

当我们想输出User属性的组合值的话,应该怎么做呢?

const { name,age,detail = `${name} 今年 ${age} `} = User ;
console.log(detail); // 输出:搞前端的半夏 今年 18 
复制代码

使用 JavaScript 对象解构别名

在 JavaScript 对象解构中,您可以为解构变量alias命名。减少变量名冲突的机会非常方便。

const User = {
  name: '搞前端的半夏',
  age: ''
}
复制代码

假设我们想用解构赋值获取age属性的值,但是代码中已经又age这个变量了,我们这个时候就需要在结构的时候定义别名。

const { age: userAge } = User;
console.log(userAge); //搞前端的半夏
复制代码

而如果使用age的话,会报错。

console.log(age);
复制代码

image-20220120093046513。*

使用对象解构处理动态名称属性

我们经常将 API 响应数据作为 JavaScript 对象处理。这些对象可能包含动态数据,因此作为客户端,我们甚至可能事先不知道属性键名称。

const User = {
  name: '搞前端的半夏',
  age: ''
}
复制代码

当我们将键作为参数传递时,我们可以编写一个返回User对象属性值的函数。这里我们使用了[],来接受参数,js会根据这个键对从对象中检索!

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

console.log(contact, name); // 空  搞前端的半夏
复制代码

在函数参数和返回值中解构对象

解构赋值传参

使用对象解构将属性值作为参数传递给函数。

const User = {
  name: '搞前端的半夏',
  age: 18
}
复制代码

name现在让我们创建一个简单的函数,该函数使用和属性值创建一条消息dept以登录到浏览器控制台。

function consoleLogUser({name, age}) {
  console.log(`${name} 今年 ${age}`); 
}
复制代码

直接将值作为函数参数传递并在内部使用它们。

consoleLogUser(User); // 搞前端的半夏 今年 18
复制代码

解构函数对象返回值

对象解构函数还有另一种用法。如果函数返回一个对象,您可以将值直接解构为变量。让我们创建一个返回对象的函数。

function getUser() {
  return {
    'name': '搞前端的半夏',
    'age': 18
  }
}
复制代码
const { age } = getUser();
console.log(age); // 18
复制代码

在循环中使用对象解构

我们将讨论的最后一个(但并非最不重要的)用法是循环解构。让我们考虑一组员工对象。我们想要遍历数组并想要使用每个员工对象的属性值。

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

您可以使用for-of循环遍历User对象,然后使用对象解构赋值语法来检索详细信息。

for(let {name, age} of employees) {
  console.log(`${name} 今年${age}岁!!!`);
}
复制代码

image-20220120095527656

Guess you like

Origin juejin.im/post/7084989788863856654