Course contentsShow
← JavaScript
Lesson 987 of 2,72322. Spread and RestFree lesson

Nested Rest in Destructuring

Use rest syntax within nested destructuring patterns for complex data extraction.

Nested Rest in Destructuring

You'll learn how to use the rest operator (...) inside nested destructuring patterns to capture remaining elements or properties from deeply structured data.

What This Means

When working with complex nested arrays or objects, you can place the rest operator at various levels of your destructuring pattern—not just at the top level. This lets you extract specific values from deep structures while collecting "everything else" at that nesting level into a single variable.

Nested Rest in Arrays

const data = [[1, 2, 3, 4], [5, 6, 7, 8]];

// Rest at the nested level
const [[first, ...restOfFirst], [second, ...restOfSecond]] = data;

console.log(first);         // 1
console.log(restOfFirst);   // [2, 3, 4]
console.log(second);        // 5
console.log(restOfSecond);  // [6, 7, 8]

Nested Rest in Objects

const user = {
  name: 'Alice',
  address: {
    street: '123 Main St',
    city: 'Boston',
    state: 'MA',
    zip: '02101'
  }
};

// Rest at the nested object level
const { name, address: { city, ...restOfAddress } } = user;

console.log(city);           // 'Boston'
console.log(restOfAddress);  // { street: '123 Main St', state: 'MA', zip: '02101' }

Mixed Nesting

const response = {
  data: [10, 20, 30, 40],
  meta: { page: 1, total: 100 }
};

const { data: [first, ...restData], meta: { page, ...restMeta } } = response;

console.log(first);      // 10
console.log(restData);   // [20, 30, 40]
console.log(page);       // 1
console.log(restMeta);   // { total: 100 }

Key Takeaway: You can use rest syntax at any level of a nested destructuring pattern to capture remaining elements or properties at that specific depth, making it easier to work with complex data structures without manually slicing or filtering.