How to Destructure into Dynamically Named Variables in Es6

How to destructure into dynamically named variables in ES6?

Short answer: it's impossible and it won't be possible.

Reasoning behind this: it would introduce new dynamically named variables into block scope, effectively being dynamic eval, thus disabling any performance optimization. Dynamic eval that can modify scope in fly was always regarded as extremely dangerous and was removed from ES5 strict mode.

Moreover, it would be a code smell - referencing undefined variables throws ReferenceError, so you would need more boilerplate code to safely handle such dynamic scope.

Destructure from dynamic key

You can rename the variables when destructuring, and the left side (preexisting name) can be in brackets like you want.

let {[key]: omitted, ...rest} = a;

Destructuring of es6 but passing dynamic variable

As 4castle pointet out, you could use Computed object property names and destructuring with an additional key/value pair variables for destructuring.

var object = { item: { a: 'a0', b: 'b0' } },    key = 'b',    value;
({ [key]: value } = object.item);
console.log(value);

Javascript object destructure with property name in variable

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);


Related Topics



Leave a reply



Submit