Search code examples
javascriptdestructuring

Javascript object destructure with property name in variable


Is it possible to destructure an object in Javascript by using a property name stored in a variable?

This is how we destructure at the moment.

const myObject = {a: 1, b: 2, c: 3};
let {a, b, c} = myObject;
console.log(a, b, c);

I would like to be able to store property names in variables:

const myObject = {banana: 1, apple: 2, strawberry: 3};
const chosenFruit = "banana";
const { [[chosenFruit]], ...theRest } = myObject;
console.log(banana); // Should be 1

For full disclosure, the reason I want to be able to do this is I want to remove the property "banana" from the object. So in my use case I want to be left with the theRest object which doesn't include the banana property, but there have been times I wanted to iterate through an array of values (e.g. days of the week) and programatically destructure objects quickly.

Is this possible? If so, how?

Thanks!


Solution

  • You could take a computed property names and rename the property (assigning to new variable names).

    const myObject = { banana: 1, apple: 2, strawberry: 3 };
    const chosenFruit = "banana";
    const { [chosenFruit]: fruit, ...theRest } = myObject;
    
    console.log(fruit); // 1
    console.log(theRest);