This technique is useful when you don't know the property name ahead of time and still want to destructure it cleanly. I often use this for deleting keys from an object. Useful in state reducers.
const keyToExtract = "email";
const user = {
name: "Sen",
email: "[email protected]",
role: "guy"
};
const { [keyToExtract]: extractedValue, ...rest } = user;
console.log(extractedValue); // [email protected]
console.log(reset); // { name: "Sen", role: "guy" }
keyToExtract
is a dynamic variable that holds the name of the key we want to pull out.- The property with the key
email
is extracted intoextractedValue
. - The rest of the object goes into
rest
.