4

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!

Thomas Clayson
  • 29,657
  • 26
  • 147
  • 224

4 Answers4

9

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);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

const myObject = {banana: 1, apple: 2, strawberry: 3};
const chosenFruit = "banana";
const newThing = { ...myObject };

delete newThing[chosenFruit];

console.log(myObject, newThing);

This version uses deconstruction to clone, and then removes the unwanted property.

Taplar
  • 24,788
  • 4
  • 22
  • 35
0

A variation with destructuring parameters:

const pick = (fruit, {[fruit]: out, ...fruits}) => [out, fruits];

const [fruit, fruits] = pick('banana', basket);

console.log(fruit);
console.log(fruits);
console.log(basket);
<script>const basket = { banana: 1, apple: 2, strawberry: 3 };</script>
customcommander
  • 17,580
  • 5
  • 58
  • 84
0

This also works for non-dynamic choices and also if you want to have the variable name same as the fruit name

const myObject = { banana: 1, apple: 2, strawberry: 3 };
const { banana, ...theRest } = myObject;

console.log(banana); // 1
console.log(theRest);
Amaarockz
  • 4,348
  • 2
  • 9
  • 27