问题
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