Computed Keys
Wrap the key in brackets to destructure a dynamically computed property name.
Wrap the key in brackets to destructure a dynamically computed property name.
const key = "name";
const { [key]: value } = { name: "Alice" }; // value = "Alice"
// Useful for dynamic access
function getField(obj, field) {
const { [field]: val = null } = obj;
return val;
}
getField({ age: 30, name: "Bob" }, "age"); // 30
Computed destructuring replaces the pattern: const val = obj[key] with a named binding.
More in JavaScript