How do you destructure nested objects?
Answer
Nested destructuring lets you extract values from deeply nested objects by mirroring the object structure on the left side of the assignment.
const data = { user: { profile: { name: 'Alice', details: { age: 28, city: 'San Francisco', }, }, },};// Nested destructuringconst { user: { profile: { name, details: { age, city }, }, },} = data;console.log(name); // "Alice"console.log(age); // 28console.log(city); // "San Francisco"Good to Know
Intermediate objects aren't available. Only the final values (name, age, city) become variables. user and profile won't be defined.
Handling missing properties. A default (= {}) prevents a TypeError when an intermediate property is undefined:
const { user: { profile: { name } = {} } = {} } = data;It does not help when the property is null, because defaults only apply to undefined. For data that may contain null, use optional chaining: data.user?.profile?.name.
Renaming. You can rename variables while destructuring:
const { user: { profile: { name: userName }, },} = data;console.log(userName); // "Alice"