JavaScript
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 destructuring
const {
user: {
profile: {
name,
details: { age, city },
},
},
} = data;
console.log(name); // "Alice"
console.log(age); // 28
console.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 - Use default values to avoid crashes:
const { user: { profile: { name } = {} } = {} } = data;Renaming - You can rename variables while destructuring:
const {
user: {
profile: { name: userName },
},
} = data;
console.log(userName); // "Alice"