Sub topic 10
Reaching into Nested Structures
This chapter assumes you already know basic array and object destructuring, renaming with property: newName, and default values with =. Nested destructuring combines those pieces. You write one pattern inside another, and the inner pattern matches the shape of the inner data.
The working model
When a pattern has another pattern where a variable name would normally go, JavaScript does three things:
- It reads the property (or the element at that position).
- It treats the value it found as the source for the inner pattern.
- It destructures that value again.
The colon in customer: { name } works the same way as in renaming. The left side is the property to read. The right side says where the value goes, and here it goes into another pattern instead of a variable.
const order = { id: 1, customer: { name: 'Lin', address: { city: 'Oslo' } } };
const { customer: { name, address: { city } } } = order;
console.log(name); // 'Lin'
console.log(city); // 'Oslo'Intermediate names are not variables
People often expect customer and address above to become variables. They don't. A key followed by a colon and a pattern is only a path. If you also want the intermediate object, list the property a second time:
const order = { customer: { name: 'Lin' } };
const { customer, customer: { name } } = order;
console.log(customer); // { name: 'Lin' }
console.log(name); // 'Lin'Mixing arrays and objects
The two pattern kinds nest inside each other freely. Array patterns match by position and object patterns match by name, at every level.
const response = {
data: { items: [{ id: 10, tags: ['new', 'sale'] }, { id: 11 }] }
};
const {
data: {
items: [{ id: firstId, tags: [firstTag] }, second]
}
} = response;
console.log(firstId); // 10
console.log(firstTag); // 'new'
console.log(second); // { id: 11 }The common error: a missing intermediate object
When a level is missing, the inner pattern tries to destructure undefined, and that throws a TypeError:
const order = { id: 1 };
try {
const { customer: { name } } = order;
} catch (err) {
console.log(err instanceof TypeError); // true
}The fix is to give the intermediate level a default of {}. When the property is undefined, the inner pattern destructures an empty object, and the inner variables end up undefined with no error:
const order = { id: 1, customer: { name: 'Lin' } };
const { customer: { name }, shipping: { city } = {} } = order;
console.log(name); // 'Lin'
console.log(city); // undefined (no TypeError, thanks to the = {} default)For arrays, use = [] the same way. You can also add defaults to the leaf values, for example shipping: { city = 'Unknown' } = {}.
| Pattern piece | Binds a variable? | Fails on missing data? |
|---|---|---|
| `customer: { name }` | Only `name` | Yes, if `customer` is undefined |
| `customer: { name } = {}` | Only `name` | No |
| `customer, customer: { name }` | `customer` and `name` | Yes, unless defaulted |
Exercise
Given const cfg = { db: { hosts: ['a.local', 'b.local'] } };, write one destructuring declaration that binds primary to 'a.local' and cacheTtl to 60 when cfg.cache or cfg.cache.ttl is missing, without throwing.
Show answer
const { db: { hosts: [primary] }, cache: { ttl: cacheTtl = 60 } = {} } = cfg; The = {} default stops the TypeError when cache is absent, and = 60 fills in ttl when it is absent.
Exercise
After const { user: { profile: { email } } } = data; runs, which variables exist?
Show answer
Only email. user and profile are paths in the pattern, not bindings.