The JavaScript Object.keys() method
The Object.keys() method returns an array of an object's own property names. Object.keys({a: 1, b: 2}) gives ["a", "b"]. Turning keys into an array is what lets you loop over, count or transform an object's properties with array methods like forEach() and map().
Overview
Objects don't have map() or forEach() of their own, so Object.keys() is the bridge: it hands you an array of the object's property names, and from there all the array methods are fair game. Want to count an object's properties? Object.keys(obj).length. Want to loop over them? Object.keys(obj).forEach(...).
It returns only the object's own enumerable keys — not inherited ones — in the order they were inserted (numeric keys aside, which sort first). That predictable ordering is something you can rely on in modern JavaScript.
It has two close siblings worth knowing together. Object.values() gives you the values instead of the keys, and Object.entries() gives you both as [key, value] pairs — ideal when you need each key and its value at once. Pick whichever matches what your loop actually needs.
Syntax
const keys = Object.keys(obj)
Object.keys({ a: 1, b: 2 }) // ["a", "b"]
Parameters
The Object.keys() method accepts the following parameters.
| Parameter | Description |
|---|---|
obj |
The object whose own enumerable property names you want as an array. |
Example
<pre id="out" style="font:15px ui-monospace,monospace"></pre>
<script>
const user = { name: 'Ada', role: 'admin', active: true };
const keys = Object.keys(user);
document.getElementById('out').textContent =
'keys: ' + keys.join(', ') + '\n' +
'count: ' + keys.length; // keys: name, role, active / count: 3
</script>
Best practices
- Use
Object.keys(obj).lengthto count an object's properties. - Loop over an object by turning its keys into an array, then using forEach() or map().
- Reach for Object.entries() when you need keys and values together.
- Remember it returns only own enumerable keys, in insertion order — inherited properties are excluded.
Frequently asked questions
What does Object.keys() return?
How do I count the properties of an object?
Object.keys(obj).length — the number of keys is the number of own properties.How do I loop over an object in JavaScript?
Object.keys(obj).forEach(key => { ... }), or use Object.entries() for keys and values.