5

I have an object that contains symbols as keys. How do I do destructuring assignment in this case?

let symbol = Symbol()
let obj = {[symbol]: ''}
let { /* how do I create a variable here, that holds the value of [symbol] property? */ } = obj

I need to know if this possible, I do know the obvious and simple workarounds, but that's not what I am asking.

UPD. Funny enough I knew how to do that but typescript produced errors, and I thought I did something wrong in JS. Here's a fix for typescript users.

Nurbol Alpysbayev
  • 19,522
  • 3
  • 54
  • 89

2 Answers2

9

Use an alias (see assigning to new variable names):

let symbol = Symbol()
let obj = { [symbol] : 'value'}
let { [symbol]: alias } = obj

console.log(alias)
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
2

Use the same syntax for destructuring as for building the object:

let symbol = Symbol()
let obj = {[symbol]: 'foo'}
let { [symbol]: myValue } = obj;
console.log(myValue);
Hero Wanders
  • 3,237
  • 1
  • 10
  • 14