JavaScript Object.keys(obj) method
The Object.keys(obj)
method in JavaScript is used to retrieve an array of a given object's own enumerable property names (keys). This method is useful for iterating over the properties of an object, particularly when you want to access the keys for further processing.
Syntax:
Parameters:
obj
: The object whose own enumerable property names are to be returned.
Return Value:
- An array containing the names of the object's own enumerable properties, in the same order as they would be iterated over in a
for...in
loop (with the exception that afor...in
loop will also enumerate properties inherited from the object's prototype).
Key Features:
- Only Own Properties:
Object.keys()
returns only the object's own properties, not properties inherited through the prototype chain. - Enumerable Properties: Only properties that are enumerable are included in the returned array. Non-enumerable properties are ignored.
- Order: The order of properties follows the same rules as those for
for...in
loops, which generally means:- Integer keys (like
1
,2
, etc.) are listed in ascending order. - String keys are listed in the order they were added.
- Symbol keys are listed in the order they were added.
- Integer keys (like
Example 1: Basic Usage
In this example, Object.keys()
retrieves the keys of the person
object and returns them as an array.
Example 2: Using with Loop
You can use the returned array to iterate over the object's properties:
In this example, Object.keys(car)
returns the keys of the car
object, and forEach
is used to log each key-value pair.
Example 3: Non-Enumerable Properties
In this example, nonEnumerable
is not included in the output because it is defined as a non-enumerable property.
Summary:
Object.keys(obj)
is a convenient method for obtaining an array of a given object's own enumerable property names.- It is commonly used for iterating over an object's properties or for quickly retrieving a list of keys for processing.
- Understanding this method is essential for working with objects in JavaScript, especially in situations where dynamic property access is needed.