破坏深层物业 [英] Destructuring deep properties

查看:101
本文介绍了破坏深层物业的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近开始使用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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆