JavaScript Reference ยท Object
Object.keys()
Reference for JavaScript Object.keys(): list an object's own enumerable property names, key order rules, counting properties and looping with examples.
Object.keys() returns an array of the names of an object's own, enumerable properties whose keys are strings. It is the standard way to find out what an object contains, count its properties, or loop over them.
The names come back as strings, even for numeric keys. For the values use Object.values(), and for both together use Object.entries().
Object.keys({ a: 1, b: 2 }); // ["a", "b"]
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
Object.keys(obj)
| Name | Description |
|---|---|
obj |
The object whose own enumerable string keys are returned. Primitives are converted to objects. |
Return value: a new array of strings.
Exceptions: a TypeError if obj is null or undefined.
Usage notes
- Own and enumerable only. Inherited properties, properties made non-enumerable and symbol keys are left out.
for...inalso visits enumerable inherited properties. - Predictable order. Integer-like keys come first in ascending numeric order; other keys follow in the order they were added.
- Keys are strings.
Object.keys([5, 6])gives["0", "1"]. Convert withNumber()if you need numbers. - Counting:
Object.keys(obj).lengthis the usual way to count properties. A property whose value isundefinedstill counts. - A snapshot. Adding or removing properties later does not change the array already returned.
- Maps and Sets are not affected: their entries are not properties, so
Object.keys(new Map([[1, 2]]))is[]. Usemap.keys(). - Hidden members:
Object.getOwnPropertyNames()includes non-enumerable ones, andReflect.ownKeys()adds symbols. - Cost: it creates a new array on each call. Store the result when you need it more than once.
Browser support
Object.keys() is available in every browser and JavaScript runtime.