search
HomeWeb Front-endJS TutorialMaster summarizes how to use object destructuring in JavaScript

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:简书. If there is any infringement, please contact admin@php.cn delete
JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Is Python or JavaScript better?Is Python or JavaScript better?Apr 06, 2025 am 12:14 AM

Python is more suitable for data science and machine learning, while JavaScript is more suitable for front-end and full-stack development. 1. Python is known for its concise syntax and rich library ecosystem, and is suitable for data analysis and web development. 2. JavaScript is the core of front-end development. Node.js supports server-side programming and is suitable for full-stack development.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.