Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 582
David Bradshaw Avatar asked Nov 18 '17 23:11

David Bradshaw


People also ask

How do I iterate through object keys?

You have to pass the object you want to iterate, and the JavaScript Object. keys() method will return an array comprising all keys or property names. Then, you can iterate through that array and fetch the value of each property utilizing an array looping method such as the JavaScript forEach() loop.

How do you iterate over all properties of an object in TypeScript?

If you want to iterate over the keys and values in an object, use either a keyof declaration ( let k: keyof T ) or Object. entries . The former is appropriate for constants or other situations where you know that the object won't have additional keys and you want precise types.


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]))
like image 64
Bergi Avatar answered Oct 14 '22 06:10

Bergi


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

like image 36
Alexander Paschenko Avatar answered Oct 14 '22 08:10

Alexander Paschenko