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
1

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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?
0

Try this:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.