How to Get All Keys of Object in JavaScript Quickly
Use
Object.keys(yourObject) to get an array of all enumerable property names (keys) of an object in JavaScript. This method returns only the object's own keys, not inherited ones.Syntax
The Object.keys() method takes one argument, the object you want to get keys from, and returns an array of strings representing the object's own enumerable property names.
Object.keys(obj): Returns an array of keys fromobj.
javascript
const keys = Object.keys(obj);
Example
This example shows how to get all keys from a simple object and print them.
javascript
const person = { name: "Alice", age: 30, city: "Wonderland" }; const keys = Object.keys(person); console.log(keys);
Output
["name", "age", "city"]
Common Pitfalls
One common mistake is expecting Object.keys() to return keys from the object's prototype chain. It only returns the object's own keys. Also, it returns only enumerable keys, so non-enumerable properties are skipped.
Another pitfall is using for...in loops without filtering, which includes inherited keys.
javascript
const parent = { inheritedKey: 1 }; const child = Object.create(parent); child.ownKey = 2; // Wrong: includes inherited keys for (const key in child) { console.log(key); // outputs 'ownKey' and 'inheritedKey' } // Right: only own keys console.log(Object.keys(child)); // outputs ['ownKey']
Output
ownKey
inheritedKey
["ownKey"]
Quick Reference
Summary tips for getting object keys:
- Use
Object.keys(obj)for own enumerable keys. - Use
Object.getOwnPropertyNames(obj)to include non-enumerable keys. - Use
for...inwithhasOwnProperty()check to avoid inherited keys.
Key Takeaways
Use Object.keys(obj) to get an array of an object's own enumerable keys.
Object.keys() does not include inherited or non-enumerable keys.
Avoid using for...in loops without filtering to prevent inherited keys from appearing.
For non-enumerable keys, use Object.getOwnPropertyNames(obj).
Always check if keys are own properties when iterating over objects.