How to destructure into dynamically named variables in ES6?

JavascriptEcmascript 6

Javascript Problem Overview


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

Javascript Solutions


Solution 1 - Javascript

It's not impossible to destructure with a dynamic key. To prevent the problem of creating dynamic variables (as Ginden mentioned) you need to provide aliases.

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

const fields = [ 'id', 'fullName' ];
const object = {};

const {[fields[0]]: id, [fields[1]]: fullName} = user;

console.log(id); // 42
console.log(fullName); // { firstName: "John", lastName: "Doe" }

To get around the problem of having to define static aliases for dynamic values, you can assign to an object's dynamic properties. In this simple example, this is the same as reverting the whole destructuring, though :)

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

const fields = [ 'id', 'fullName' ];
const object = {};

({[fields[0]]: object[fields[0]], [fields[1]]: object[fields[1]]} = user);

console.log(object.id); // 42
console.log(object.fullName); // { firstName: "John", lastName: "Doe" }

sources:

Solution 2 - Javascript

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.

Solution 3 - Javascript

Paul Kögel's answer is great, but I wanted to give a simpler example for when you need only the value of a dynamic field but don't need to assign it to a dynamic key.

let obj = {x: 3, y: 6};
let dynamicField = 'x';

let {[dynamicField]: value} = obj;

console.log(value);

Solution 4 - Javascript

As discussed before, you can't destruct into dynamically named variables in JavaScript without using eval.

But you can get a subset of the object dynamically, using reduce function as follows:

const destruct = (obj, ...keys) => 
  keys.reduce((a, c) => ({ ...a, [c]: obj[c] }), {});

const object = { 
  color: 'red',
  size: 'big',
  amount: 10,
};

const subset1 = destruct(object, 'color');
const subset2 = destruct(object, 'color', 'amount', 'size');
console.log(subset1);
console.log(subset2);

Solution 5 - Javascript

You can't destruct without knowing the name of the keys or using an alias for named variables

// you know the name of the keys
const { id, fullName } = user;

// use an alias for named variables
const { [fields[0]]: id, [fields[1]]: fullName } = user; 

A solution is to use Array.reduce() to create an object with the dynamic keys like this:

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

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

const obj = fields.reduce((acc, k) => ({ ...acc, ...(user.hasOwnProperty(k) && { [k]: user[k] }) }), {});

for(let k in obj) {
  console.log(k, obj[k]);
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAnasView Question on Stackoverflow
Solution 1 - JavascriptPaul KögelView Answer on Stackoverflow
Solution 2 - JavascriptGindenView Answer on Stackoverflow
Solution 3 - JavascriptjunvarView Answer on Stackoverflow
Solution 4 - JavascriptMuhammet EnginarView Answer on Stackoverflow
Solution 5 - JavascriptFractionView Answer on Stackoverflow