0

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
lipenco
  • 1,358
  • 5
  • 16
  • 30

2 Answers2

3

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.

FZs
  • 16,581
  • 13
  • 41
  • 50
  • interesting! I didn't know it was possible to destructure a nested object. With the above operation you also declared a variable named "questions", or just the "id" one? – Mario Vernari Oct 11 '19 at 14:52
0

Try this:

const { questions } = blogPost;
const { id } = questions[0];
Mario Vernari
  • 6,649
  • 1
  • 32
  • 44