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:

const keysArray = Object.keys(obj);

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 a for...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.

Example 1: Basic Usage

const person = { name: 'Alice', age: 30, job: 'Developer' }; const keys = Object.keys(person); console.log(keys); // Output: ["name", "age", "job"]

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:

const car = { make: 'Toyota', model: 'Camry', year: 2020 }; Object.keys(car).forEach(key => { console.log(`${key}: ${car[key]}`); }); // Output: // make: Toyota // model: Camry // year: 2020

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

const obj = {}; Object.defineProperty(obj, 'nonEnumerable', { value: 'I am non-enumerable', enumerable: false }); obj.enumerable = 'I am enumerable'; const keys = Object.keys(obj); console.log(keys); // Output: ["enumerable"]

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.