Search code examples
javascriptsymbols

Iterate through object properties with Symbol keys


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


Solution

  • 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