Iterate through object properties with Symbol keys

ⅰ亾dé卋堺 提交于 2019-12-31 01:51:11

问题


I need to iterate through an object that has Symbols for keys. The following code returns an empty array.

const FOO = Symbol('foo');
const BAR = Symbol('bar');

const obj = {
  [FOO]: 'foo',
  [BAR]: 'bar',
}

Object.values(obj)

How can I iterate the values in obj so that I get ['foo', 'bar']?


回答1:


Object.values only gets the values of all enumerable named (string-keys) properties.

You need to use Object.getOwnPropertySymbols:

console.log(Object.getOwnPropertySymbols(obj).map(s => obj[s]))



回答2:


You can iterate over all the keys of Object (String and Symbol keys) with

Reflect.ownKeys()

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Reflect/ownKeys



来源:https://stackoverflow.com/questions/47372305/iterate-through-object-properties-with-symbol-keys

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