Javascript 简明教程

JavaScript - Nested Destructuring

Nested Destructuring

JavaScript 中的 Nested Destructuring 允许我们从 nested 对象和数组中提取数据。对象(或数组)可以包含它内部的另一个对象(或数组),称为嵌套对象(或数组)。展开嵌套对象或数组称为嵌套解构。我们可以使用解构从对象或数组中提取全部或部分数据。

The Nested Destructuring in JavaScript allows us to extract data from nested objects and arrays. An object (or array) can contain another object (or array) inside itself, known as a nested object (or array). Unpacking the nested objects or arrays is called nested destructuring. We can extract all or some data from the objects or arrays using destructuring.

我们可以将从嵌套数组或对象中提取的数据分配给变量。这被称为嵌套解构赋值。当使用嵌套解构从嵌套数组或对象中获取一些值时,您必须遵循数组或对象的结构。

We can assign the extracted data from nested array or object to the variables. This is referred as nested destructuring assignment. When using nested destructuring to get some values from a nested array or object, you have to follow the structure of the array or object.

Nested Object Destructuring

本部分将演示 JavaScript 中的嵌套对象解构。

This section will demonstrate nested object destructuring in JavaScript.

Syntax

JavaScript 中嵌套对象解构的语法如下:

The syntax of nested object destruction in JavaScript is as follows −

const {prop1, prop2: {nestedprop1, nestedprop2}} = obj;

在以上语法中,prop1 是该对象的属性,并且 prop2 属性包含嵌套对象,具有 nestedprop1 和 nestedprop2 属性。

In the above syntax, prop1 is a property of the object, and the prop2 property contains the nested object, having nestedprop1 and nestedprop2 properties.

Example

在以下示例中,car 对象包含 brand、model 和 info 属性。info 属性包含包含 price 和 color 属性的嵌套对象。

In the example below, the car object contains the brand, model, and info properties. The info property contains the nested object containing the price and color properties.

我们解构了嵌套对象并在输出中打印了变量的值。

We have destructured the nested object and printed the values of the variables in the output.

<html>
<body>
   <p id = "output"> </p>
   <script>
      const car = {
         brand: "Hyundai",
         model: "Verna",
         info: {
            price: 1200000, // Nested properties
            color: "white",
         }
      }
      const { brand, model, info: { price, color } } = car; // Destructuring
      document.getElementById("output").innerHTML =
	   `Brand: ${brand} <br> Model: ${model} <br> Price: ${price} <br> Color: ${color}`;
   </script>
</body>
</html>
Brand: Hyundai
Model: Verna
Price: 1200000
Color: white

Example: Nested object destructuring and renaming variables

以下代码演示了在解构嵌套对象属性的同时重命名变量。

The below code demonstrates that you can rename the variables while unpacking the nested object properties.

我们已经将 brand、model、price 和 color 变量重命名为 company、name、cost 和 carColor。

We have renamed the brand, model, price, and color variables to company, name, cost, and carColor.

<html>
<body>
<p id = "output"> </p>
<script>

   const car = {
      brand: "Hyundai",
      model: "Verna",
      info: {
         price: 1200000, // Nested properties
         color: "white",
      }
   }
   // Destructuring
   const {brand: company, model: name, info: {price: cost, color: carColor }} = car;

   document.getElementById("output").innerHTML =
   `Company: ${company}, Name: ${name}, Cost: ${cost}, Color: ${carColor}`;
</script>
</body>
</html>
Company: Hyundai, Name: Verna, Cost: 1200000, Color: white

Example: Nested object destructuring and default values

您可以使用赋值运算符为变量分配默认值。每当对象的特定属性未定义时,它都会使用默认值初始化变量。

You can use the assignment operator to assign the default values to the variables. Whenever particular property of the object is undefined, it initializes the variable with the default value.

在此,我们重命名了每个变量并分配了默认值。'science' 属性未在 grades(嵌套对象)对象中定义。因此,代码在输出中打印其默认值。

Here, we have renamed each variable and assigned default values. The 'science' property is not defined in the grades (nested object) object. So, the code prints its default value in the output.

<html>
<body>
   <p id = "output"> </p>
   <script>
      const student = {
         firstName: "Sam",
         lastName: "Raina",
         grades: {
            English: 75,
         }
      };

      const { firstName: name = "Jay",
         lastName: surname = "Shah",
         grades: { English: eng = 0, Science: sci = 0 }
      } = student;

      document.getElementById("output").innerHTML =
      `Name: ${name} <br> Surname: ${surname} <br> English: ${eng} <br> Science: ${sci}`;
   </script>
</body>
</html>
Name: Sam
Surname: Raina
English: 75
Science: 0

Example: Nested object destructuring and rest operator

使用剩余运算符可以将剩余的属性收集到一个对象中。

The rest operator allows you to collect the remaining properties into a single object.

在以下代码中,grades 对象包含 4 个不同的属性。我们使用剩余运算符将 Maths 属性的值存储在 Maths 变量中,将其他属性存储在 'allGrades' 变量中。'allGrades' 是包含 3 个属性的对象。

In the below code, the grades object contains 4 different properties. We have stored the value of the Maths property in the Maths variables and other properties in the 'allGrades' variable using the rest operator. The 'allGrades' is an object containing 3 properties.

<html>
<body>
   <p id = "output"> </p>
   <script>
      const student = {
         firstName: "Kunal",
         lastName: "Karma",
         grades: {
            English: 75,
            Maths: 87,
            SocialScience: 90,
            Science: 80,
         }
      };
      const { firstName, lastName, grades: { Maths, ...allGrades } } = student;
      document.getElementById("output").innerHTML =
		`firstName: ${firstName} <br>
		 lastName: ${lastName} <br>
		 Maths: ${Maths} <br>
		 allGrades: ${JSON.stringify(allGrades)} <br>
		 `;
   </script>
</body>
</html>
firstName: Kunal
lastName: Karma
Maths: 87
allGrades: {"English":75,"SocialScience":90,"Science":80}

Nested Array Destructuring

本部分将演示 JavaScript 中的嵌套数组解构。

This section will demonstrate nested array destructuring in JavaScript.

Syntax

在 JavaScript 中展开嵌套数组元素(嵌套数组解构)的语法如下:

The syntax to unpack nested array elements (nested array destructuring) in JavaScript is as follows −

const [a, [b, c], d] = arr;

在以上语法中,我们将嵌套数组元素存储在 b 和 c 变量中。

In the above syntax, we store the nested array elements in the b and c variables.

Example

在以下代码中,arr 数组包含嵌套数组。我们将嵌套数组元素展开到 b 和 c 变量中。在输出中,您可以观察 b 和 c 变量的值。

In the below code, the arr array contains the nested array. We unpack the nested array elements into the variables b and c. In the output, you can observe the values of the b and c variables.

<html>
<body>
   <p id = "output"> </p>
   <script>
      const arr = [10, [15, 20], 30];
      const [a, [b, c], d] = arr;
      document.getElementById("output").innerHTML =
      "a = " + a + ", b = " + b + ", c = " + c + ", d = " + d;
   </script>
</body>
</html>
a = 10, b = 15, c = 20, d = 30

Example: Skipping elements of the nested array

赋值解构允许您跳过嵌套数组的元素。此处,arr 数组包含两个嵌套数组。在对嵌套数组进行解构时,我们将跳过每个嵌套数组的第一个元素。

Assignment destructuring allows you to skip the elements of the nested array. Here, the arr array contains two nested arrays. We skip the first element of each nested array while destructuring the nested array.

<html>
<body>
   <p id = "output"> </p>
   <script>
      const arr = [2, [3, 4], [9, 10]];
      const [a, [, b], [, c]] = arr;
      document.getElementById("output").innerHTML =
      "a = " + a + ", b = " + b + ", c = " + c;
   </script>
</body>
</html>
a = 2, b = 4, c = 10

Example: Nested array destructuring and default values

你可以在解构嵌套数组时为变量分配默认值,就像分配给对象一样。

You can assign default values to the variables like objects while destructuring the nested arrays.

在此处,arr [3,4] 的第一个嵌套数组包含两个元素。在解构时,我们跳过了前两个元素,并使用变量 p 来获取第三个元素,但嵌套数组只包含两个元素。因此,变量 p 的值是默认值 29。

Here, the first nested array of arr [3, 4] contains two elements. While destructuring, we skipped the first two elements and used the variable p to get the third element, but the nested array contains only two elements. So, the value of the variable p is a 29 default value.

<html>
<body>
   <p id = "output"> </p>
   <script>
      const arr = [2, [3, 4], [9, 10]];
      const [, [, , p = 29], [, q]] = arr;
      document.getElementById("output").innerHTML =
      "p = " + p + ", q = " + q;
   </script>
</body>
</html>
p = 29, q = 10

Example: Nested array destructuring and rest operator

可以将 rest 运算符与嵌套数组解构结合使用。此处变量 b 存储第一个嵌套数组的其余元素,变量 c 存储父数组的剩余元素,包括第二个嵌套数组和最后一个数组元素。

You can use the rest operator with nested array destructuring. Here, variable b stores the remaining elements of the first nested array, and variable c stores the remaining elements of the parent array, which includes the second nested array and last array element.

<html>
<body>
   <p id = "output"> </p>
   <script>
      const arr = [[6, 7, 8, 9], [10, 11, 12, 13], 14];
      const [[a, ...b], ...c] = arr
      document.getElementById("output").innerHTML =
      "a = " + a + "<br> b = " + b + "<br> c = " + c;
   </script>
</body>
</html>
a = 6
b = 7,8,9
c = 10,11,12,13,14

Array Within Object – Nested Destructuring

有的时候,我们需要解构包含数组的对象。让我们通过下面的例子来理解一下。

Sometimes, we need to destructure the object containing the array. Let’s understand it via the example below.

Example

在下面的例子中,numbers 对象的 num2 属性包含数组。我们解构对象属性并在输出中打印值。

In the example below, the num2 property of the numbers object contains the array. We destructure the object properties and print the values in the output.

<html>
<body>
   <p id = "output"> </p>
   <script>
      const numbers = {
         num1: 10,
         num2: [40, 6, 5],
      }
      const {num1, num2: [a, b, c]} = numbers;
      document.getElementById("output").innerHTML =
      "num1 = " + num1 + ", a = " + a + ", b = " + b + ", c = " + c;
   </script>
</body>
</html>
num1 = 10, a = 40, b = 6, c = 5

Object Within Array – Nested Destructuring

在某些情况下,数组也可以包含对象,你需要从数组中解构对象。

In some cases, an array can also contain the object, and you need to destructure the object from the array.

Example

在下面的代码中,numbers 数组包含包含 p 和 q 属性的对象。

In the below code, the numbers array contains the object containing the p and q properties.

然后,我们解构数组并解包对象属性。

After that, we destructure the array and unpack the object properties.

<html>
<body>
   <p id = "output"> </p>
   <script>
      const numbers = [10, { p: 20, q: 30 }]
      const [a, { p, q }] = numbers;
      document.getElementById("output").innerHTML =
      "a = " + a + ", p = " + p + ", q = " + q;
   </script>
</body>
</html>
a = 10, p = 20, q = 30