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
fields
were changed to be an empty array then you would be creating no variables and any code after that would be jeopardized. Using a const with literals ensures that risk could be determined beforehand but something likefields = nonliteralvar
would create problems. – Heronry