Computed Property Names in Destructuring
You'll learn how to destructure object properties when the property name itself is stored in a variable or needs to be calculated.
The Core Idea
Sometimes you don't know the exact property name you want to extract at write-time—it might be stored in a variable or determined dynamically. Normally, destructuring looks for literal property names, but bracket notation lets you use a computed (variable) key instead.
Think of it like a restaurant order: instead of saying "I want the Caesar salad" (literal), you're saying "I want whatever is written on this card" (computed). The card contains the name, and you get that dish.
The Syntax
Instead of the familiar { propertyName } syntax, wrap the variable in square brackets:
const user = {
name: 'Alice',
age: 30,
city: 'Paris'
};
const prop = 'age';
const { [prop]: value } = user;
console.log(value); // 30
Notice the pattern: { [variableName]: newVariableName }. The variable prop holds the string 'age', so JavaScript looks up user.age and assigns it to value.
Real-World Example
function extractField(obj, fieldName) {
const { [fieldName]: extracted } = obj;
return extracted;
}
const product = { id: 101, title: 'Laptop', price: 999 };
console.log(extractField(product, 'title')); // 'Laptop'
console.log(extractField(product, 'price')); // 999
Combining with Other Features
You can use computed property names alongside defaults and renaming:
const key = 'status';
const data = { status: 'active' };
const { [key]: currentStatus = 'unknown' } = data;
console.log(currentStatus); // 'active'
Key Takeaway: Use bracket notation { [variableName]: newName } when destructuring to extract properties whose names are stored in variables or computed at runtime.