简体   繁体   English

如何从数组中解构嵌套变量

[英]How to destructure nested variable from the array

my obj looks like that:我的 obj 看起来像这样:

blogPost: {
  questions: 
    [
      {
        id: 234
      }
    ]
}

I would like to destructure id , but this doesn't seem correct.我想解构id ,但这似乎不正确。

const {questions[0]: {id}} = blogPost

Use array destructuring as well to make it work:也可以使用数组解构来使其工作:

{questions:[{id}]}=blogPost

Alternatively, you can use object destructuring on arrays as well (arrays are objects), but that is less semantical:或者,您也可以在 arrays 上使用 object 解构(数组是对象),但这不太语义:

{questions:{'0':{id}}}=blogPost

That accesses the property in a different way: array destructuring calls Symbol.iterator method to iterate over the array, while object destructuring does a [[Get]] operation on the specified keys only.这以不同的方式访问属性:数组解构调用Symbol.iterator方法来迭代数组,而 object 解构只对指定的键执行[[Get]]操作。

Try this:尝试这个:

const { questions } = blogPost;
const { id } = questions[0];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM