List own enumerable properties
Enumerate an object's directly declared public fields without traversing its prototype chain.
JavaScript · Function
Object.keys() returns an array of an object's own enumerable string-keyed property names. It excludes inherited and non-enumerable properties.
Object.keys() examines the supplied value and returns a new array containing the names of its own enumerable properties when those names are strings. It excludes inherited and non-enumerable properties, preserves the property-enumeration order, and handles primitive inputs through object coercion except for null and undefined, which cause a TypeError.
Object.keys(obj)| Name | Type | Description |
|---|---|---|
obj | object | The value whose own enumerable string-keyed property names should be listed. |
An array of strings representing the given object's own enumerable string-keyed property keys.
const user = { name: "Ada", age: 36 };
for (const key of Object.keys(user)) {
console.log(key, user[key]);
}Iterates over the object's own enumerable string-keyed properties and uses each key to read its value.
Enumerate an object's directly declared public fields without traversing its prototype chain.
Build a new collection by transforming or filtering property names.
Validate or inspect the available enumerable fields in configuration or input data.
Object.keys() returns an array of an object's own enumerable string-keyed property names. It does not include inherited, non-enumerable, or Symbol-keyed properties.
Follow-up: How would you include non-enumerable string properties? Use Object.getOwnPropertyNames(), which returns both enumerable and non-enumerable own string properties.
The returned array uses the same property order exposed by a for...in loop for the object's own enumerable string properties. The key array contains strings, not values.
Follow-up: How can you obtain keys and values together? Use Object.entries(), which returns key-value pairs.
The argument is coerced to an object unless it is null or undefined. Strings can yield enumerable index keys, whereas other primitive values produce an empty array.
Follow-up: What happens with Object.keys(null)? It throws a TypeError because null cannot be coerced to an object.
Object.values()Object.entries()Object.getOwnPropertyNames()for...in