Friday, May 17, 2024
-6
rated 0 times [  1] [ 7]  / answers: 1 / hits: 42762  / 8 Years ago, fri, march 11, 2016, 12:00:00

Let's suppose I have the following object:



const user = { 
id: 42,
displayName: jdoe,
fullName: {
firstName: John,
lastName: Doe
}
};


And that I want only the id and fullName.



I will do the following :



const { id, fullName } = user


Easy-peasy, right?



Now let's suppose that I want to do the destructuring based on the value of another variable called fields.



const fields = [ 'id', 'fullName' ]


Now my question is : How can I do destructuring based on an array of keys?



I shamelessly tried the following without success:



let {[{...fields}]} = user and let {[...fields]} = user. Is there any way that this could be done?



Thank you


More From » ecmascript-6

 Answers
18

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.


[#62980] Tuesday, March 8, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jackie

Total Points: 442
Total Questions: 107
Total Answers: 94

Location: Honduras
Member since Sun, Dec 26, 2021
2 Years ago
jackie questions
Sat, Sep 18, 21, 00:00, 3 Years ago
Wed, Jul 14, 21, 00:00, 3 Years ago
;