5 common scenarios and examples of JavaScript destructuring assignment

5 common scenarios and examples of JavaScript destructuring assignment

Preface

Destructuring assignment syntax is a JavaScript expression that can be used to take properties/values ​​out of an object/array and assign them to other variables. This syntax is the ECMAscript 6 specification introduced a new syntax that makes it easier to get values ​​from arrays and objects.

1. Extract data

Let's take a look at how to deconstruct objects in JavaScript, starting with this simple example of a product object.

const product = {
    id: 1,
    title: "Nike Air Zoom Pegasus 38",
    product_image: "/resources/products/01.jpeg",
    shown: "White/Pure Platinum/Midnight Navy/Wolf Grey",
    price: 120,
};
const { id, price, title } = product;

Then, the corresponding properties can be accessed as follows:

console.log(id); // 1
console.log(price); // 120
console.log(title); // Nike Air Zoom Pegasus 38

Destructuring can make the code clearer and more concise. What if you need to deconstruct a more complex object? That is, an object within an object.

Now suppose you need to get the attributes of one of the products from the product list data, as follows:

const products = [
    {
        id: 1,
        title: "Nike Air Zoom Pegasus 38",
        price: 120,
    },
    {
        id: 2,
        title: "Nike Air Zoom Alphafly NEXT%",
        price: 275,
    },
    {
        id: 3,
        title: "Nike Zoom Fly 4",
        price: 89.0,
    },
];

Here, the product list is nested several levels deep. If you need to access the product information, you can deconstruct as many levels as possible to get the properties of the product object.

const [tmp, { id, title, price }] = products;
console.log(id); // 2
console.log(title); // Nike Air Zoom Alphafly NEXT%
console.log(price); // 275

The above code is only used to demonstrate its usage. It is not recommended to obtain object information in the array in this way during project development.

Usually, data lists do not necessarily have to be arrays. In terms of acquisition efficiency, map objects are more efficient than arrays. The above data can be changed into a map object as follows:

const products = {
    1: {
        title: "Nike Air Zoom Pegasus 38",
        price: 120,
    },
    2: {
        title: "Nike Air Zoom Alphafly NEXT%",
        price: 275,
    },
    3: {
        title: "Nike Zoom Fly 4",
        price: 89.0,
    },
};
const {
    2: { id, title, price },
} = products;
console.log(id); // 2
console.log(title); // Nike Air Zoom Alphafly NEXT%
console.log(price); // 275

In JavaScript, data can be variables and methods, so destructuring assignment is also suitable for defining function parameters, as follows:

const printArticle = ({ title, remark }) => {
    console.log(title);
    console.log(remark);
};
printArticle({
    title: "JavaScript destructuring assignment",
    remark: "Introduction to practical scenarios of destructuring assignment",
});

When using frameworks such as React or Vue, there are many places for deconstruction assignment, such as the introduction of methods and so on.

2. Alias ​​value

If you want to create a variable with a different name than the property, you can use the alias feature of object destructuring.

const { identifier: aliasIdentifier } = expression;

identifier is the name of the property to be accessed and aliasIdentifier is the variable name. The specific usage is as follows:

const products = {
    1: {
        title: "Nike Air Zoom Pegasus 38",
        price: 120,
    },
    2: {
        title: "Nike Air Zoom Alphafly NEXT%",
        price: 275,
    },
    3: {
        title: "Nike Zoom Fly 4",
        price: 89.0,
    },
};
const {
    2: { price: productPrice },
} = products;

console.log(productPrice); // 275

3. Dynamic properties

You can extract to variable attributes using dynamic names (the attribute name is known at runtime):

const { [propName]: identifier } = expression;

The propName expression should evaluate to the property name (usually a string), and the identifier should indicate the variable name created after destructuring, as follows:

const products = {
    1: {
        title: "Nike Air Zoom Pegasus 38",
        price: 120,
    },
    2: {
        title: "Nike Air Zoom Alphafly NEXT%",
        price: 275,
    },
    3: {
        title: "Nike Zoom Fly 4",
        price: 89.0,
    },
};
const productKey = "1";
const { [productKey]: product } = products;
console.log(product); // { title: 'Nike Air Zoom Pegasus 38', price: 120 }

In the above code, the value of product can be updated by updating the value of productKey.

4. Rest in Object Deconstruction

Adds rest syntax to destructuring, Rest properties collect those remaining enumerable property keys that have not been picked up by the destructuring pattern.

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

After destructuring, the variable identifier contains the property value. A rest variable is a plain object with the rest properties.

const product = {
    title: "Nike Air Zoom Pegasus 38",
    price: 120,
    quantity: 5,
    category_id: 1,
    reviews: 9830,
    total: 45,
};
const { title, ...others } = product;
console.log(others); // { price: 120, quantity: 5, category_id: 1, reviews: 9830, total: 45 }

For arrays, you can use Rest to get the first and last values:

const numbers = [1, 2, 3];
const [head, ...tail] = numbers;
console.log(head); // 1
console.log(tail); // [ 2, 3 ]

5. Default Values

As mentioned earlier, you can assign default values ​​to arrays when destructuring them:

const RGBA = [255, 34];
const [R, G, B = 0, A = 1] = RGBA;
console.log(R); // 255
console.log(G); // 34
console.log(B); // 0
console.log(A); // 1

This ensures that there is a default value when B and A are not defined.

Summarize

Destructuring is a very useful feature that was added to the ES6 version of JavaScript. Destructuring allows you to quickly and easily extract properties or data from objects and arrays into separate variables. It works well with nested objects and can be assigned to arrays using the ... operator.

This concludes this article about 5 common scenarios and examples of JavaScript destructuring assignment. For more relevant JS destructuring assignment examples, please search 123WORDPRESS.COM’s previous articles or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Summary of common usage of javascript destructuring assignment under ES6
  • An article to help you understand JavaScript destructuring assignment
  • A practical guide to JavaScript destructuring assignment
  • JavaScript destructuring assignment detailed explanation
  • JS ES new feature of variable decoupling assignment
  • Detailed description of shallow copy and deep copy in js
  • Detailed explanation of JS ES6 variable destructuring assignment
  • JavaScript assignment, the difference between shallow copy and deep copy

<<:  A small problem about null values ​​in MySQL

>>:  A question about border-radius value setting

Recommend

How to start multiple MySQL databases on a Linux host

Today, let’s talk about how to start four MySQL d...

Docker configures the storage location of local images and containers

Use the find command to find files larger than a ...

Solution to the problem that Navicat cannot remotely connect to MySql server

The solution to the problem that Navicat cannot r...

Basic concepts and common methods of Map mapping in ECMAScript6

Table of contents What is a Mapping Difference be...

Example code for implementing a hollow mask layer with CSS

Contents of this article: Page hollow mask layer,...

Detailed explanation of the difference between uniapp and vue

Table of contents 1. Simple page example 2.uni-ap...

JavaScript imitates Xiaomi carousel effect

This article is a self-written imitation of the X...

Tutorial on downloading, installing, configuring and using MySQL under Windows

Overview of MySQL MySQL is a relational database ...

A brief analysis of the differences between undo, redo and binlog in MySQL

Table of contents Preface 【undo log】 【redo log】 【...

Tips for implementing multiple borders in CSS

1. Multiple borders[1] Background: box-shadow, ou...

In-depth explanation of MySQL user account management and permission management

Preface The MySQL permission table is loaded into...

CSS3 overflow property explained

1. Overflow Overflow is overflow (container). Whe...

Detailed process of upgrading glibc dynamic library in centos 6.9

glibc is the libc library released by gnu, that i...

How to read the regional information of IP using Nginx and GeoIP module

Install GeoIP on Linux yum install nginx-module-g...