Iterate through object properties with Symbol keys

Viewed 5840

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']?

2 Answers

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]))
Related