-2

In case, we need to use dynamic key to parse data out of some nested object and destructure it as below, is it required to be assigned to some alias as below. I am getting compilation error otherwise.

const { [dynamicKey] : isAliasVarReqd } = data.something[dynamicKey]
copenndthagen
  • 49,230
  • 102
  • 290
  • 442
  • 7
    If you don't assign it to an alias, what will the variable name be? – Barmar Jun 11 '21 at 16:23
  • Please edit thq question and show the problem code, not the working code. – Barmar Jun 11 '21 at 16:25
  • 2
    JavaScript doesn't have dynamic local variables, so how would you use the value after you destructure it? – Barmar Jun 11 '21 at 16:26
  • 3
    "*You need to give it a variable to assign to. You cannot use "computed" variable names, as that would go against the rules of static scope resolution for identifiers*." https://stackoverflow.com/a/37040523/3082296 – adiga Jun 11 '21 at 16:28

1 Answers1

2

Assuming we have 'x' as a value that has to be destructured, we can pass this dynamically into our destructuring syntax using square brackets syntax [removeProp], just like an object lookup (instead this will create a new variable based off the dynamically passed value).

const someData = { x: 1, y: 2, z: 3 };
const removeProp = 'x';

const { [removeProp]: remove } = someData;

console.log(remove); // 1

Because we’re dynamically constructing a new variable, we need to use : remove to reassign it to a new name.

Prashant Reddy
  • 309
  • 1
  • 3
  • 8