Getting JavaScript object key list
Use Object.keys(obj)
to obtain an array of enumerable keys of an object.
Example:
This method is widely used for iterating through object properties or validating structure of objects.
Number of keys
Next, simply count the number of keys in the object using keys.length
:
Now you have a magic number that reveals how packed your object really is.✨
Quick dive into for...in
loop
A for...in
loop traverses all enumerable properties of an object, including those it inherits. To simply enumerate an object's own properties, use the hasOwnProperty()
method:
Trust me, you don't want any unexpected prototype chain surprises here.
Alternative world with the Underscore.js library
The power of JavaScript libraries like Underscore.js brings relief for heavy-duty object manipulation tasks:
- Use
_.keys(obj)
for the same taste asObject.keys(obj)
. _.map(obj, fn)
: Rising above simple object key retrieval, this utility function creates an array by transforming each value obtained from all keys.
Dealing with objects - strategies and nuances
Counting keys and applying per key logic
Working with keys often requires performing some operation on each key and/or knowing the count of keys. Here's a quick way to do that:
Custom function to retrieve keys
For those seeking a safe journey to the world of keys, a custom method is the perfect guide:
Dealing with non-enumerable keys
Got non-enumerable properties in the mix? Object.getOwnPropertyNames(obj)
comes to the rescue:
Pitfalls and things to watch out for
Non-object values
Object.keys()
requires an argument of type object. Passing non-object values throws an error:
Non-enumerable keys
Object.keys()
only considers enumerable keys. Non-enumerable keys don't make the list:
Older JavaScript engines
Remember, ES5 methods like Object.keys()
might not be available in older environments. In such cases, use a polyfill like this:
Was this article helpful?