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
Best Cross-Browser Method to Capture Ctrl+S with Jquery
Basic JavaScript Promise Implementation Attempt
JavaScript Variables Declare Outside or Inside Loop
How to Count Certain Elements in Array
ASP.NET Postback with JavaScript
Firebase: Setting Additional User Properties
Why Does Array.Prototype.Push Return the New Length Instead of Something More Useful
How to Watch for a Route Change in Angularjs
How to Detect When the Mouse Leaves the Window
Dynamic Function Name in JavaScript
Palindrome Check in JavaScript
Best Way to Call an Asynchronous Function Within Map
JSON.Stringify() Array Bizarreness with Prototype.Js
Using Jquery to Replace One Tag with Another
JavaScript - How to Extract Filename from a File Input Control
Using JavaScript to Display a Blob
Unexpected Behavior Using Array Map on an Array Initialized with Array Fill