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

    技术2022-07-11  125

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

    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:

    例如,要同时引用b和y ,可以使用逗号:

    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

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

    Processed: 0.010, SQL: 9