ES6: destructuring an object with symbols as keys

六眼飞鱼酱① 提交于 2020-02-24 10:08:15

问题


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.


回答1:


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

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

console.log(alias)



回答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);


来源:https://stackoverflow.com/questions/54004346/es6-destructuring-an-object-with-symbols-as-keys

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!