三层嵌套对象数组怎么解构_嵌套解构

三层嵌套对象数组怎么解构

Destructuring in JavaScript can initially feel confusing but the truth is that destructuring can make your code a bit more logical and straight forward. Destructuring does look a bit more complex when you're looking for a property several objects deep, so let's have a look at how to do that!

使用JavaScript进行结构分解最初可能会感到困惑,但事实是,结构分解可以使您的代码更具逻辑性和直截了当。 当您要寻找一个深几个对象的属性时,解构的过程看起来会更加复杂,所以让我们来看看如何做到这一点!

Simple destructuring looks as follows:

简单的解构如下所示:

const { target } = event;

Here we use {} and = to name a variable the same as the property name (you can also use an alias while destructuring!). Grabbing a nested object value is a bit more complicated, however:

在这里,我们使用{}=来命名与属性名称相同的变量( 在解构时也可以使用别名! )。 但是,获取嵌套对象的值要复杂一些:

// Object for testing
const x = { y: { z: { a: 1, b: 2} } }

// Get "b"
const { y: { z: { b } } } = x;

console.log(b); // 2
console.log(z); // z is not defined
console.log(y); // y is not defined

Here we an object-like syntax with {} and : to set a var based on the nested obect property. Note that only the last nested property is given as a variable; the parents we reference along the way do not.

在这里,我们使用{}:的类对象语法来基于嵌套的obect属性设置var。 注意,只有最后一个嵌套属性作为变量给出; 我们沿途推荐的父母没有。

To get a reference to both b and y, for example, you can use a comma:

例如,要同时引用by ,可以使用逗号:

const { y, y: { z: { b } } } = x;

console.log(b); // 2
console.log(y); // {z: {…}}

Destructuring can take a while to get used to but, the more I use it, the more I appreciate how simple my code can be: no "dot" hell and less overall code!

解构可能需要一段时间才能习惯,但是,我使用它的次数越多,我就越欣赏我的代码多么简单:没有“点”地狱,总的代码也更少!

翻译自: https://davidwalsh.name/nested-destructuring

三层嵌套对象数组怎么解构

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值