inspection
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.getOwnPropertyNames(obj) Parameters
| Parameter | Purpose |
|---|---|
| obj | The object whose own string-keyed properties are to be returned |
| returns | Array of all own string property names |
Examples
const o = Object.defineProperty({}, 'hidden', { value: 1, enumerable: false });
o.visible = 2;
console.log(Object.getOwnPropertyNames(o)); Logs [ 'hidden', 'visible' ]
console.log(Object.getOwnPropertyNames([1, 2, 3])); Logs [ '0', '1', '2', 'length' ] — length is non-enumerable
console.log(Object.keys({ a: 1 }));
console.log(Object.getOwnPropertyNames({ a: 1 })); Both log [ 'a' ] when all keys are enumerable
const s = Symbol('id');
console.log(Object.getOwnPropertyNames({ [s]: 1, name: 'x' })); Logs [ 'name' ] — Symbols excluded; use getOwnPropertySymbols for those
Gotcha
Includes non-enumerable string keys but STILL excludes Symbol keys. Use Reflect.ownKeys(obj) to get strings + Symbols + non-enumerables in one call.
Related methods
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.getOwnPropertyDescriptor
Returns the property descriptor for an own property on the given object, or undefined if the property does not exist. Descriptors describe writability, enumerability, configurability, and getters/setters.
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.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.