In this post, I will talk about destructuring, first introduced in the ES6 version of Javascript. Destructuring is a way of extracting properties from an object or values from an array into variables.
在这篇文章中,我将讨论在Java的ES6版本中首次引入的解构。 销毁是将对象的属性或数组中的值提取为变量的一种方法。
As mentioned destructuring was first introduced in the ES6 version of Javascript, so the earlier version of Javascript does not support the destructuring syntax, in that cases either you have to use the traditional way to unpack object and arrays, or you use Babel or anything that will compile your code to the previous version for use.
如前所述,在Java的ES6版本中首次引入了解构,因此较早版本的Javascript不支持解构语法,在这种情况下,您必须使用传统的方式来解压缩对象和数组,或者使用Babel或任何其他会将您的代码编译为以前的版本以供使用。
An object is a collection of properties, and a property is an association between a name (or key) and a value. Sometimes we need a few properties of the object assigned to variables. Before destructuring was introduced we used the dot operator to access properties from an object like in the below code, and you can keep doing that. Or you can use destructuring to make this process cleaner and simple.
对象是属性的集合,而属性是名称(或键)和值之间的关联。 有时我们需要分配给变量的对象的一些属性。 在引入解构之前,我们使用点运算符从对象中访问属性,如下面的代码所示,您可以继续这样做。 或者,您可以使用解构使此过程更加简洁。
const user = {
name: 'John Doe',
age: 12,
gender: 'male'
}
// Extracting properties using dot operator
const userName = user.name;
const userAge = user.age;
console.log(userName, userAge) // John Doe 12// Extracting properties using destructuring
const { name, age } = user;console.log(name, age) // John Doe 12
Here in the destructuring what happening is that the name
and age
properties from the user are assigned to name
and age
variables.
在进行销毁时,发生的是将用户的name
和age
属性分配给name
和age
变量。
NOTE: Although order of properties does not matter, the name of properties matter, if I add any other variable for destructuring I will get undefined assigned to it. Let’s see a small implementation for this
注意:尽管属性的顺序无关紧要,但是属性的名称很重要,如果我添加其他任何要进行销毁的变量,则会得到未定义的赋值。 让我们来看一个小的实现
const user = {
name: 'John Doe'
}const { name, age } = user;
console.log(name, age) // 'John Doe', undefined
age
isundefined
because there is no property namedage
in the user object. So if you are destructuring an object you need to be specific with variable names you use.
age
是undefined
,因为没有命名属性age
在用户对象。 因此,如果要销毁对象,则需要使用所使用的变量名进行特定化。
分解为您选择的变量名 (Destructuring into variable name of your choice)
Destructuring objects with the variable names the same as the property name might cause trouble like redeclaring the variable in the same scope. Overcoming this challenge is easy, let’s see how.
销毁具有与属性名称相同的变量名称的对象可能会导致麻烦,例如在同一范围内重新声明变量。 克服这一挑战很容易,让我们看看如何。
const userOne = {
name: 'John Doe',
age: 20
}const userTwo = {
name: 'Jane Doe',
age: 19
}const { name: userOneName, age: userOneAge } = userOne
const { name: userTwoName, age: userTwoAge } = userTwoconsole.log(userOneName, userOneAge); // John Doe 20
console.log(userTwoName, userTwoAge); // Jane Doe 19
In the above code I have destructured the
userOne
propertiesname
andage
touserOneName
anduserOneAge
.在上面的代码中,我将
userOne
属性的name
和age
userOneName
userOneAg e
为userOneName
和userOneAg e
。
{ name: userOneName } = userOne
This means that the property name
from userOne
is assigned to the variable userOneName
.
这意味着将userOne
的属性name
分配给变量userOneName
。
销毁时的默认值 (Default values while destructuring)
When destructuring we can provide default values to the variables, so in case if the property is not found in the object, a default value is assigned to the variable. The Default value is only assigned when a property is not found in the object.
进行解构时,我们可以为变量提供默认值,因此,如果在对象中找不到属性,则将默认值分配给变量。 仅当在对象中找不到属性时才分配默认值。
const user = {
name: 'John Doe',
}const { gender: userGender = 'male', age = 20 } = user;
console.log(userGender, age) //male, 20
In the above code snippet, there is no gender
andage
property in the user object. So male
is assigned to userGender
variable and 20 are assigned to age.
在以上代码段中,用户对象中没有gender
和age
属性。 因此,将male
分配给userGender
变量,将20分配给年龄。
获取具有剩余属性的对象(Rest) (Get object with remaining properties (Rest))
Destructuring remaining properties is also a similar action as we earlier performed in our array destructuring. Let’s see that for the object too. It is also known as the Rest operation of Spread and Rest operator (...
)
解构剩余属性也与我们先前在数组解构中执行的操作类似。 让我们来看看对象。 也称为Spread and Rest运算符的Rest操作( ...
)
const userOne = {
name: 'John Doe',
gender: 'male',
age: 20,
isStudent: true,
}const { isStudent, ...userData } = userOne
console.log(userData, isStudent)
// { name: 'John Doe', gender: 'male', age: 20 } true
The isStudent
variable is assigned the property isStudent
from userOne
, and the remaining properties of userOne
are assigned to userData
. To achieve this we used the rest operator.
isStudent
变量从userOne
分配了isStudent
属性,而userOne
的其余属性分配给了userData
。 为此,我们使用了rest运算符。
Note: To do proper destructuring the remaining variable should be at the rightmost part in the variable declaration. Or there will be an error
注意:要正确地进行结构分解,剩余变量应位于变量声明的最右侧。 否则会有错误
‘ SyntaxError: Rest element must be last element’
'SyntaxError:Rest元素必须是最后一个元素'
const userTwo = {
name: 'John Doe',
gender: 'male',
age: 19,
isStudent: true,
}const { isStudent, name, gender, age, ...userDataTwo } = userTwo
console.log(isStudent, name, gender, age, userDataTwo)
// true 'John Doe' 'male' 19 {}
Here when we will destructure the object, all the properties will be assigned to corresponding variables before reaching the variable userDataTwo
. Now userDataTwo
will not get assigned anything, now the question is what will happen if nothing is assigned to it. One can assume that it will be undefined but actually will be an empty object.
在这里,当我们分解对象时,所有属性将在到达变量userDataTwo
之前分配给相应的变量。 现在, userDataTwo
将不会获得任何分配,现在的问题是,如果未分配任何内容,将会发生什么。 可以假定它是未定义的,但实际上是一个空对象。
Here comes a question of why some variables are
undefined
when not matched and others just empty. Let get this one clear. When a property is not found in the object, the variable with the same name gets undefined, but when we use rest operator then the variable is an empty object.这里有一个问题,为什么有些变量在不匹配时
undefined
,而另一些变量只是空的。 让我们弄清楚这一点。 当在对象中找不到属性时,具有相同名称的变量将变得不确定,但是当我们使用rest运算符时,该变量是一个空对象。
两步声明和分配 (Two-step declaration and assignment)
In destructuring, it is not mandatory to destructure at the time of variable declaration (not applicable for const
variable). To destructure after variable declaration we have to use parenthesis around the expression, otherwise, it will be a syntax error
在解构中,在变量声明时不强制进行解构(不适用于const
变量)。 要在变量声明后进行解构,我们必须在表达式周围使用括号,否则将出现语法错误
“Declaration or statement expected”.
“预期的声明或声明”。
const user = {
name: 'John Doe',
age: 12,
gender: 'male'
}let name, age;
({ name, age } = user);
console.log(name, age) // John Doe 12
嵌套对象的解构 (Destructuring for nested objects)
The object can have nested objects or arrays. When destructuring nested objects we can destructure them by nesting as the objects or arrays are nested. When we have the property, then we can break it into smaller parts by destructuring.
该对象可以具有嵌套的对象或数组。 解构嵌套对象时,我们可以在嵌套对象或数组时通过嵌套来解构它们。 当我们拥有该属性时,可以通过分解将其分成较小的部分。
const userData = {
name: 'John Doe',
age: 22,
gender: 'male',
friends: ['Phoebe','Ross','Monica','Chandler','Joey','Rachel'],
medium: {
username: 'johndoe',
blogs: 2,
organization: 'Central Perk',
claps: 5,
}
}const { friends:[ friendOne, friendTwo ] } = userData
const {
medium: { username, organization: userOrganization }
} = userDataconsole.log(friendOne, friendTwo) // Phoebe Ross
console.log(username, userOrganization) // johndoe Central Perkconsole.log(friends) // ReferenceError: friends is not defined
console.log(medium) // referenceError: medium is not defined
Here theuserData
object has a property named friends
which carries an array and medium
property which carries an object. To destructure and extract values from the array we have to first get the property and then destructure the array. To destructure and extract properties from the medium we have to extract the medium first then destructure it again at the same moment.
这里的userData
对象具有一个名为friends
的属性,该属性带有一个数组,而medium
属性则具有一个对象。 要从数组中解构并提取值,我们必须首先获取属性,然后对数组进行解构。 要从介质中解构并提取属性,我们必须先提取介质,然后在同一时间再次对其进行解构。
包装全部 (Wrapping it all up)
As you can see from the above examples, destructuring is a clean and nice way to work with objects and arrays. I have covered almost everything basically needed to use destructuring in your code. I hope this helps you understand destructuring in Javascript and you feel more confident when working with arrays and objects.
从上面的示例中可以看到,销毁是一种处理对象和数组的干净而不错的方法。 我已经介绍了在代码中使用解构所需的几乎所有内容。 我希望这可以帮助您了解Javascript中的结构分解,并在使用数组和对象时感到更有信心。
翻译自: https://engineering.wisflux.com/destructuring-objects-a30f64c66088