How to Get All Keys (Including Symbols) from an Object in JavaScript or Node.js

We recently added a new feature to the @supercharge/map package: create a map from an object. Objects and maps represent key-value pairs. We iterated through the object’s keys to create the related entries in the map.

While iterating through the object keys, we noticed that properties were missing in the used for…in loop. For example, symbols or non-enumerable properties weren’t available in the map. But they were on the object! Why are they missing?

This tutorial shows you how to retrieve all keys of an object, including symbols!

Node.js Series Overview

Get All Keys Including Symbols From a JavaScript Object

JavaScript objects can have non-enumerable properties. Non-enumerable properties are available when accessing them directly, like obj.nonEnumerableProperty. But these properties won’t show up when looping over an object’s properties using a for…in loop.

You can find more details about an object’s property enumerability in the MDN docs.

A way to iterate through all properties of an object is using the Reflect.ownKeys method. Reflect.ownKeys returns the list of enumerable, non-enumerable, and symbol keys of a given object.

Here’s a sample function returning the keys of a given object:

/**
 * Returns all keys from the given `obj`ect.
 *
 * @returns {Array<string>}
 */
function keysOf(obj) {  
    return Reflect.ownKeys(obj)
}

You may use the keysOf function like this:

const users = {  
  1: 'Marcus',
  'user:2': 'Norman',
  [Symbol.for('christian')]: 'Christian'
}

const keys = keysOf(users)  
// ['1', 'user:2', Symbol(christian)]

Please notice: Reflect.ownKeys() doesn’t return inherited enumerable properties. This can happen when working with class inheritance. You may not retrieve the properties of your base class using this approach with an inherited class instance.

Also, notice that JavaScript coerces all keys to a string. The example contains a key-value pair 1: 'Marcus where the key 1 is a number. Everything is a string when retrieving an object’s keys in JavaScript.

Enjoy!


Mentioned Resources

Explore the Library

Find interesting tutorials and solutions for your problems.