Renaming While Destructuring Nested Properties
You'll learn how to give custom variable names to values buried deep inside nested objects while destructuring them.
Drilling Down and Renaming in One Move
When you destructure nested properties, you might want to rename them for clarity or to avoid naming conflicts. You can combine the colon syntax you already know for renaming with the pattern matching for nested structures.
Think of it like providing directions: "Go into the user object, find the address property, then grab the city inside it, but call it userCity in our code." You're specifying both the path to follow and the name to use.
The Syntax Pattern
Here's how it looks:
const data = {
user: {
profile: {
name: 'Alice',
age: 30
}
}
};
// Navigate to profile.name, but rename it to 'userName'
const { user: { profile: { name: userName } } } = data;
console.log(userName); // 'Alice'
console.log(name); // ReferenceError: name is not defined
The pattern is: { outerKey: { innerKey: { deepKey: newName } } }.
You can rename at any level:
const config = {
database: {
connection: {
host: 'localhost',
port: 5432
}
}
};
const { database: { connection: dbConnection } } = config;
console.log(dbConnection); // { host: 'localhost', port: 5432 }
console.log(connection); // ReferenceError: connection is not defined
Notice that dbConnection now holds the entire connection object, but the original connection name doesn't exist in your scope.
Key Takeaway: Use colon syntax (oldName: newName) at any nesting level to rename variables while destructuring—perfect for avoiding conflicts or making deeply nested properties more readable.