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 create your own image using Dockerfile

1. Create an empty directory $ cd /home/xm6f/dev ...

Summary of related functions for Mysql query JSON results

The JSON format field is a new attribute added in...

Solve the problems encountered when installing MySQL 8.0 on Win10 system

The problems and solutions encountered when insta...

Detailed explanation of keywords and reserved words in MySQL 5.7

Preface The keywords of MySQL and Oracle are not ...

Introduction to the use of anchors (named anchors) in HTML web pages

The following information is compiled from the Int...

MySQL reports an error: Can't find file: './mysql/plugin.frm' solution

Find the problem Recently, I found a problem at w...

Thoroughly understand JavaScript prototype and prototype chain

Table of contents Preface Laying the foundation p...

How to check where the metadata lock is blocked in MySQL

How to check where the metadata lock is blocked i...

JavaScript offsetParent case study

1. Definition of offsetParent: offsetParent is th...

Util module in node.js tutorial example detailed explanation

Table of contents Starting from type judgment Str...

Implementation of CSS dynamic height transition animation effect

This question originated from a message on Nugget...

JavaScript type detection method example tutorial

Preface JavaScript is one of the widely used lang...