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']
?
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.
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.
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]))
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With