The Object getOwnPropertySymbols() method
By Flavio Copes
Learn how the JavaScript Object.getOwnPropertySymbols() method returns an array of the Symbol keys defined on an object, a companion to the ES2015 Symbol type.
Object.getOwnPropertySymbols() returns an array of all the symbol properties defined directly on an object.
Symbols are an ES2015 feature, and this method was introduced in ES2015 as well.
A symbol is a unique value you can use as an object property key, as an alternative to strings. The interesting part is that symbol keys are hidden from the usual ways we inspect objects.
Example:
const dog = {}
const r = Symbol('Roger')
const s = Symbol('Syd')
dog[r] = {
name: 'Roger',
age: 6
}
dog[s] = {
name: 'Syd',
age: 5
}
Object.getOwnPropertySymbols(dog) //[ Symbol(Roger), Symbol(Syd) ]
We created two symbols and used them as keys on the dog object. Object.getOwnPropertySymbols() gives us both back in an array.
Why do we need this method?
Symbol keys don’t show up anywhere else. Object.keys(), for...in, and JSON.stringify() all skip them:
Object.keys(dog) //[]
JSON.stringify(dog) //'{}'
That’s by design. Symbols are meant for properties that shouldn’t clash with regular string keys, like internal metadata a library attaches to your objects.
Object.getOwnPropertySymbols() is the escape hatch. It’s the one method that lists those hidden keys, which is handy when you’re debugging and wonder what a library stored on your object.
If you want string keys and symbol keys in a single array, use Reflect.ownKeys() instead.
Using the symbols you get back
The array contains the actual symbol values, so you can use them to read the properties:
const symbols = Object.getOwnPropertySymbols(dog)
dog[symbols[0]] //{ name: 'Roger', age: 6 }
If the object has no symbol properties, you get an empty array:
const cat = { name: 'Milo' }
Object.getOwnPropertySymbols(cat) //[]
Notice the method only returns own properties. Symbols defined on the prototype are not included, which matches how Object.getOwnPropertyNames() works for string keys.
A pitfall with symbol equality
Every symbol is unique, even when two symbols share the same description. You can’t recreate a symbol to access a property:
dog[Symbol('Roger')] //undefined
This is a brand new symbol, different from the r we used earlier. The description 'Roger' is just a label for debugging, it doesn’t identify the symbol.
So if you lost the original symbol reference, Object.getOwnPropertySymbols() is the only way to get it back and read the value.
Related posts about js: