JavaScript object destructuring usage analysis (detailed examples)
This article brings you relevant knowledge about object destructuring usage analysis in JavaScript. I hope it will be helpful to you.
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 }
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;
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;
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', } }
If we use . to go back and forth with the value of phone, it will take two times.
const phone = User.contact.phone;
If we use destructuring assignment: the writing is as follows:
const {contact:{phone}}=User consosle.log(phone) // 输出10.
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: '搞前端的半夏', }
or the attribute has no specific value:
const User = { name: '搞前端的半夏', age: '' }
When we use destructuring assignment: regardless of whether age exists If there are attributes, the age variable will be created.
const { name, age } = employee;
When User.age has no specific value, we can use
const { name, age=18 } = employee;
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
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: '' }
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); //搞前端的半夏
And if you use age, an error will be reported.
console.log(age);
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: '' }
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; }
const contact = getPropertyValue('contact'); const name = getPropertyValue('name'); console.log(contact, name); // 空 搞前端的半夏
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 }
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}`); }
Pass values directly as function parameters and use them internally.
consoleLogUser(User); // 搞前端的半夏 今年 18
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 } }
const { age } = getUser(); console.log(age); // 18
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 } ];
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}岁!!!`); }
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!

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

SublimeText3 Chinese version
Chinese version, very easy to use

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

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.
