Home  >  Article  >  Web Front-end  >  Master summarizes how to use object destructuring in JavaScript

Master summarizes how to use object destructuring in JavaScript

coldplay.xixi
coldplay.xixiforward
2020-12-02 16:58:587436browse

JavaScript column introduces how to use object deconstruction

Master summarizes how to use object destructuring in JavaScript

##Related free learning recommendations: javascript (Video)

Object destructuring is a useful JavaScript feature that can extract properties from an object and bind them to variables.

Even better, object destructuring can extract multiple properties in a single statement, properties can be accessed from nested objects, and a default value can be set if the property does not exist.

In this article, I will explain how to use object decomposition in JavaScript.

Directory

1.Require object decomposition

2.Extract attributes
3.Extract multiple attributes
4.Default value
5.Alias
6. Extract attributes from nested objects
7. Extract dynamic name attributes
8. Destroyed objects
9. Common use cases
10. Summary

1. Require objects Decomposition

Suppose you want to extract some properties of an object. In a pre-ES2015 environment, you would need to write the following code:

var hero = {
  name: 'Batman',
  realName: 'Bruce Wayne'
};

var name     = hero.name;var realName = hero.realName;
name;     // => 'Batman',
realName; // => 'Bruce Wayne'
Property

hero.nameThe value is assigned to the variable name. Assign the same hero.realName value to realName.

This method of accessing a property and assigning it to a variable requires boilerplate code. By writing

var name = hero.name, you have to mention name twice in the binding, for the same realName.

This is where object destructuring syntax is useful: you can read a property and assign its value to a variable without repeating the property name. Not only that, you can read multiple properties of the same object in one statement!

Let's refactor the above script and apply object decomposition to access properties

name and realName:

const hero = {
  name: 'Batman',
  realName: 'Bruce Wayne'
};

const { name, realName } = hero;
name;     // => 'Batman',
realName; // => 'Bruce Wayne'

const { name , realName } = hero is the object destruction and allocation. This statement defines the variables name and realName, and then assigns to their attribute values ​​hero.name and hero.realNamecorrespondigly.

Compare the two methods of accessing object properties:

const name     = hero.name;
const realName = hero.realName;

// is equivalent to:

const { name, realName } = hero;
It can be seen that since the property names and object variables are not repeated, the decomposition of the object is more convenient.

2. Extract attributes

The basic syntax for object destructuring is very simple:

const { identifier } = expression;
where

identifier is the name of the property to be accessed, expression Should evaluate to an object. After destruction, the variable identifier contains the attribute value.

This is the equivalent code using property accessors:

const identifier = expression.identifier;
Let's try object decomposition in practice:

const hero = {
  name: 'Batman',
  realName: 'Bruce Wayne'
};

const { name } = hero;
name; // => 'Batman'
The statement

const { name } = herodefines the variable name and initializes it with the value of hero.nameproperty.

3. Extract multiple properties

To break the object into multiple properties, enumerate any number of properties and

,add commas in between:

const { identifier1, identifier2, ..., identifierN } = expression;
where

identifier1,...identifierN are the names of the properties to be accessed and the expression should evaluate to objects. After destruction, the variables identifier1identifierN contain the corresponding attribute values.

Here is the equivalent code:

const identifier1 = expression.identifier1;
const identifier2 = expression.identifier2;
// ...
const identifierN = expression.identifierN;
Let’s look at the example from the first part again, where 2 properties are extracted:

const hero = {
  name: 'Batman',
  realName: 'Bruce Wayne'
};

const { name, realName } = hero;
name;     // => 'Batman',
realName; // => 'Bruce Wayne'

const { name, realName } = hero Create 2 variables name and realName assign the corresponding attributes hero.name and the value of hero.realName.

4.Default value

If the destructured object does not have the properties specified in the destructuring assignment, the variable is assigned to

undefined. Let's see how it happens:

const hero = {
  name: 'Batman',
  realName: 'Bruce Wayne'
};

const { enemies } = hero;
enemies;     // => undefined
The destructured variable

enemies is undefined because the property enemies is not in the object hero exists.

Fortunately, if the property does not exist in the destructured object, you can set a default value. The basic syntax is as follows:

const { identifier = defaultValue } = expression;
where

identifier is the name of the property to be accessed and expression should evaluate to an object. After destruction, the variable identifier contains the attribute value, or defaultValue is assigned to the variable if the identifier attribute does not exist.

This is the equivalent code:

const identifier = expression.identifier === undefined ? 
        defaultValue : expression.identifier;
Let’s change the previous code example and use the default value function:

const hero = {
  name: 'Batman',
  realName: 'Bruce Wayne'
};

const { enemies = ['Joker'] } = hero;
enemies;     // => ['Joker']
Now,

undefined The variable enemies defaults to ['Joker'].

5. Alias

If you want to create a variable with a different name than the attribute, you can use the alias function of object decomposition.

const { identifier: aliasIdentifier } = expression;

identifier is the name of the property to be accessed, aliasIdentifier is the name of the variable, and expression should evaluate to an object. After destruction, the variable aliasIdentifier contains the attribute value.

Equivalent code:

const aliasIdentifier = expression.identifier;
This is an example of object decomposition alias functionality:

const hero = {
  name: 'Batman',
  realName: 'Bruce Wayne'
};

const { realName: secretName } = hero;
secretName; // => 'Bruce Wayne'

看一下const { realName: secretName } = hero,解构定义了一个新变量secretName(别名变量),并为其分配了值hero.realName

6.从嵌套对象中提取属性

在前面的示例中,对象很简单:属性具有原始数据类型(例如字符串)。

通常,对象可以嵌套在其他对象中。换句话说,某些属性可以包含对象。

在这种情况下,您仍然可以从深处使用对象分解和访问属性。基本语法如下:

const { nestedObjectProp: { identifier } } = expression;

nestedObjectProp是保存嵌套对象的属性的名称。identifier是要从嵌套对象访问的属性名称。expression应该评估变形后的对象。

销毁后,变量identifier包含嵌套对象的属性值。

上面的语法等效于:

const identifier = expression.nestedObjectProp.identifier;

您可以从中提取属性的嵌套级别不受限制。如果要从深处提取属性,只需添加更多嵌套的花括号:

const { propA: { propB: { propC: { .... } } } } = object;

例如,对象hero包含一个嵌套对象{ city: 'Gotham'}

const hero = {
  name: 'Batman',
  realName: 'Bruce Wayne',
  address: {
    city: 'Gotham'
  }
};

// Object destructuring:
const { address: { city } } = hero;
city; // => 'Gotham'

通过对象解构,const { address: { city } } = hero您可以city从嵌套对象访问属性。

7.提取动态名称属性

您可以将具有动态名称的属性提取到变量中(属性名称在运行时是已知的):

const { [propName]: identifier } = expression;

propNameexpression应该计算为属性名称(通常是字符串),并且identifier应该指示在解构之后创建的变量名称。第二个expression应该评估要分解的对象。

没有对象分解的等效代码:

const identifier = expression[propName];

让我们看一个prop包含属性名称的示例:

const hero = {
  name: 'Batman',
  realName: 'Bruce Wayne'
};

const prop = 'name';
const { [prop]: name } = hero;
name; // => 'Batman'

const { [prop]: name } = hero是一个对象分解,将变量赋给namevalue hero[prop],其中prop是一个保存属性名称的变量。

8.销毁后的物体

rest语法对于在解构之后收集其余属性很有用:

const { identifier, ...rest } = expression;

哪里identifier是要访问的属性名称,expression应评估为一个对象。

销毁后,变量identifier包含属性值。rest变量是具有其余属性的普通对象。

例如,让我们提取属性name,但保留其余属性:

const hero = {
  name: 'Batman',
  realName: 'Bruce Wayne'
};

const { name, ...realHero } = hero;
realHero; // => { realName: 'Bruce Wayne' }

破坏const { name, ...realHero } = hero提取财产name

同时,剩余的属性(realName在这种情况下)被收集到变量realHero:中{ realName: 'Bruce Wayne' }

9.常见用例

9.1将属性绑定到变量

如之前的许多示例所示,对象解构将属性值绑定到变量。

对象解构可以给变量赋值使用声明constletvar。甚至分配给一个已经存在的变量。

例如,以下是使用let语句解构的方法:

// let
const hero = {
  name: 'Batman',
};

let { name } = hero;
name; // => 'Batman'

如何使用var语句来破坏结构:

// var
const hero = {
  name: 'Batman',
};

var { name } = hero;
name; // => 'Batman'

以及如何解构为已声明的变量:

// existing variable
let name;

const hero = {
  name: 'Batman',
};

({ name } = hero);
name; // => 'Batman'

我发现将for..of循环与对象解构相结合以立即提取属性是令人满意的:

const heroes = [
  { name: 'Batman' },
  { name: 'Joker' }
];

for (const { name } of heroes) {  console.log(name); // logs 'Batman', 'Joker'
}

9.2功能参数解构

通常,对象分解可以放置在发生分配的任何位置。

例如,您可以在函数的参数列表内破坏对象:

const heroes = [
  { name: 'Batman' },
  { name: 'Joker' }
];

const names = heroes.map(
  function({ name }) {    return name;
  }
);

names; // => ['Batman', 'Joker']

function({ name })解构函数参数,创建一个name保存name属性值的变量。

10.总结

对象解构是一项强大的功能,可让您从对象中提取属性并将这些值绑定到变量。

我特别喜欢对象分解的简洁语法和在一条语句中提取多个变量的能力。

希望我的帖子对您了解对象分解的有用!

The above is the detailed content of Master summarizes how to use object destructuring in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:jianshu.com. If there is any infringement, please contact admin@php.cn delete