inspection
Object.keys
Returns an array of a given object's own enumerable string-keyed property names. The order matches a normal for...in loop but excludes inherited and non-enumerable properties.
Object.keys(obj) Parameters
| Parameter | Purpose |
|---|---|
| obj | The object whose enumerable own string-keyed properties are to be returned |
| returns | Array of own enumerable string property names |
Examples
console.log(Object.keys({ a: 1, b: 2, c: 3 })); Logs [ 'a', 'b', 'c' ]
const arr = ['x', 'y', 'z'];
console.log(Object.keys(arr)); Logs [ '0', '1', '2' ] — array indices as strings
const o = Object.create({ inherited: 1 }, { own: { value: 2, enumerable: true } });
console.log(Object.keys(o)); Logs [ 'own' ] — inherited properties are skipped
const s = Symbol('id');
console.log(Object.keys({ [s]: 1, name: 'Ada' })); Logs [ 'name' ] — Symbol keys are excluded
Gotcha
Returns only OWN enumerable STRING keys — inherited properties, non-enumerable properties, and Symbol keys are excluded. Use Reflect.ownKeys() to get everything including Symbols and non-enumerables.
Related methods
Object.values
Returns an array of a given object's own enumerable string-keyed property values. Introduced in ES2017 as a companion to Object.keys.
Object.entries
Returns an array of a given object's own enumerable string-keyed [key, value] pairs. Useful for iterating objects with for...of destructuring or converting to a Map.
Object.getOwnPropertyNames
Returns an array of all own string-keyed property names, including non-enumerable ones (but not Symbol keys). Useful for introspection where Object.keys is too restrictive.
Object.hasOwn
Returns true if the specified object has the given property as its own property (not inherited). Added in ES2022 as the recommended replacement for Object.prototype.hasOwnProperty.
Object.prototype.hasOwnProperty
Instance method returning true if the object has the specified property as its own (non-inherited) property. Superseded by the safer static Object.hasOwn in ES2022.