Advertisement
Advanced JavaScript, Destructuring, Spread & Rest

How do you destructure nested objects and arrays in one statement?

Short answer

Destructuring patterns can be nested to match the shape of complex data, pulling deeply nested values into flat variables in a single expression.

Save JavaScript mock interview
Advertisement
AModel answer
Destructuring patterns can be nested to match the shape of complex data, pulling deeply nested values into flat variables in a single expression.
const response = { data: { user: { name: 'Sam' } }, meta: { ids: [1, 2] } };
const { data: { user: { name } }, meta: { ids: [firstId] } } = response;
console.log(name, firstId); // 'Sam' 1
Real-world example
Extracting a deeply nested field from a complex GraphQL or REST API response in one line.
Likely follow-ups
  • What happens if an intermediate nested property is undefined during this kind of destructuring?
Related topics