Get array of object's keys
Pull out all the keys from an object using Object.keys()
trick:
Unpacking Object.keys()
Working with nested objects
What if our object is nested like this Russian matryoshka doll?
To extricate the keys buried in nested objects, plunge into recursion:
🎉 Voila! Now we have all the keys, even those playing hide-n-seek deep inside!
The legacy issue
Some older browsers don't understand the cutting edge Object.keys()
. For them, we can use a polyfill like ES5-shim. jQuery project? Don't sweat:
When objects have a history
Object.keys()
only cares about own properties and not inherited. So if you need inherited properties, here's the workaround:
Not just keys, but pairs
Sometimes your job isn't simply to fetch keys. You need both key-value pairs. ES6 has your back with Object.entries()
:
Combine this with Array.prototype.reduce()
for even cooler maneuvers!
Detective work on keys
Just remember, all keys are unique and treated as — guess what — strings! Watch your back when dealing with numeric keys.
Sorting play
The order of keys is not under your control (engines' whim!). Need sorted keys? Do this:
Action time with Object.keys()
Armed with Object.keys()
, you can create marvels. Here are some:
-
Filtering objects by property values. E.g., get keys of items with high inventory.
-
Create a new representation from keys.
-
Collapse object properties to derive a single value.
When things go awry...
... don't panic. Check if:
- Your argument to
Object.keys()
is indeed an object. - No object properties are non-enumerable (They won't show up).
- You're not dealing with host objects (Like DOM elements), they can mess with your code.
Was this article helpful?