简体   繁体   中英

How to destructure nested variable from the array

my obj looks like that:

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

I would like to destructure id , but this doesn't seem correct.

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:

{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.

Try this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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