解构深层属性 [英] Destructuring deep properties
问题描述
我最近开始使用 ES6 的 解构赋值语法并开始熟悉这个概念.我想知道是否可以使用相同的语法提取嵌套属性.
I recently started using ES6's destructuring assignment syntax and started to get familiar with the concept. I was wondering if it's possible to extract a nested property using the same syntax.
例如,假设我有以下代码:
For example, let's say I have the following code:
let cagingIt = {
foo: {
bar: 'Nick Cage'
}
};
我知道我可以通过以下方式访问提取 foo
到一个变量中:
I know I am able to access extract foo
into a variable by doing:
// where foo = { bar: "Nick Cage" }
let { foo } = cagingIt;
但是,是否可以提取深度嵌套的属性,例如 bar
.也许是这样的:
However, is it possible to extract a deeply nested property, like bar
. Perhaps something like this:
// where bar = "Nick Cage"
let { foo[bar] } = cagingIt;
我已尝试查找有关此事的文档,但无济于事.任何帮助将不胜感激.谢谢!
I've tried finding documentation on the matter but to no avail. Any help would be greatly appreciated. Thank you!
推荐答案
有一种方法可以使用此语法处理嵌套对象和数组.鉴于上述问题,解决方案如下:
There is a way to handle nested objects and arrays using this syntax. Given the problem described above, a solution would be the following:
let cagingIt = {
foo: {
bar: 'Nick Cage'
}
};
let { foo: {bar: name} } = cagingIt;
console.log(name); // "Nick Cage"
在本例中,foo
指的是属性名称foo".在冒号之后,我们使用 bar
来引用属性bar".最后,name
充当存储值的变量.
In this example, foo
is referring to the property name "foo". Following the colon, we then use bar
which refers to the property "bar". Finally, name
acts as the variable storing the value.
至于数组解构,你可以这样处理:
As for array destructuring, you would handle it like so:
let cagingIt = {
foo: {
bar: 'Nick Cage',
counts: [1, 2, 3]
}
};
let { foo: {counts: [ ct1, ct2, ct3 ]} } = cagingIt;
console.log(ct2); // prints 2
它遵循与对象相同的概念,只是您可以使用数组解构并存储这些值.
It follows the same concept as the object, just you are able to use array destructuring and store those values as well.
希望这有帮助!
这篇关于解构深层属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!