javascript 解构深层属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34211076/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Destructuring deep properties
提问by Dom
I recently started using ES6's destructuringassignment 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.
我最近开始使用 ES6 的解构赋值语法并开始熟悉这个概念。我想知道是否可以使用相同的语法提取嵌套属性。
For example, let's say I have the following code:
例如,假设我有以下代码:
let cagingIt = {
foo: {
bar: 'Nick Cage'
}
};
I know I am able to access extract foo
into a variable by doing:
我知道我可以foo
通过执行以下操作来访问提取到变量中:
// where foo = { bar: "Nick Cage" }
let { foo } = cagingIt;
However, is it possible to extract a deeply nested property, like bar
. Perhaps something like this:
但是,是否可以提取深度嵌套的属性,例如bar
. 也许是这样的:
// 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!
我曾尝试查找有关此事的文档,但无济于事。任何帮助将不胜感激。谢谢!
回答by Dom
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"
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.
在本例中,foo
指的是属性名称“foo”。在冒号之后,我们使用bar
which 指代属性“bar”。最后,name
充当存储值的变量。
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.
它遵循与对象相同的概念,只是您可以使用数组解构并存储这些值。
Hope this helps!
希望这可以帮助!
回答by etoxin
If you have lodash installed, you can use one of the following:
如果您安装了 lodash,则可以使用以下其中一种:
_.get
_。得到
var object = { 'a': [{ 'b': { 'c': 3 } }] };
_.get(object, 'a[0].b.c');
// => 3
or if you need multiple keys.
或者如果您需要多个键。
_.at
_。在
var object = { 'a': [{ 'b': { 'c': 3 } }, 4] };
_.at(object, ['a[0].b.c', 'a[1]']);
// => [3, 4]
You can also safely pair _.at()
up with with Array destructuring. Handy for json responses.
您还可以安全地_.at()
与数组解构配对。方便的 json 响应。
[title, artist, release, artwork] = _.at(object, [
'items[0].recording.title',
'items[0].recording.artists[0].name',
'items[0].recording.releases[0].title',
'items[0].recording.releases[0].artwork[0].url'
]);