Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 251
Thomas Clayson Avatar asked Aug 29 '26 18:08

Thomas Clayson


1 Answers

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);
like image 167
Nina Scholz Avatar answered Sep 01 '26 08:09

Nina Scholz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!