最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - ES6: destructuring an object with symbols as keys - Stack Overflow

programmeradmin7浏览0评论

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.

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.

Share Improve this question edited Jan 2, 2019 at 11:17 Nurbol Alpysbayev asked Jan 2, 2019 at 10:02 Nurbol AlpysbayevNurbol Alpysbayev 22k5 gold badges67 silver badges99 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 9

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

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

console.log(alias)

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);
发布评论

评论列表(0)

  1. 暂无评论