JavaScript Object.entries(obj) method


The Object.entries(obj) method in JavaScript is used to retrieve an array of a given object's own enumerable property [key, value] pairs. This method is useful for iterating over the properties of an object when you need both the keys and their corresponding values.

Syntax:

const entriesArray = Object.entries(obj);

Parameters:

  • obj: The object whose own enumerable property [key, value] pairs are to be returned.

Return Value:

  • An array of arrays, where each inner array consists of two elements: the property key and the corresponding value. The order of the entries is the same as they would be iterated over in a for...in loop (excluding properties inherited from the object's prototype).

Key Features:

  • Only Own Properties: Object.entries() 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 entries follows the same rules as those for for...in loops:
    • 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 entries = Object.entries(person); console.log(entries); // Output: [["name", "Alice"], ["age", 30], ["job", "Developer"]]

In this example, Object.entries() retrieves the key-value pairs of the person object and returns them as an array of arrays.

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.entries(car).forEach(([key, value]) => { console.log(`${key}: ${value}`); }); // Output: // make: Toyota // model: Camry // year: 2020

In this example, Object.entries(car) returns the entries 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 entries = Object.entries(obj); console.log(entries); // Output: [["enumerable", "I am enumerable"]]

In this example, nonEnumerable is not included in the output because it is defined as a non-enumerable property.

Summary:

  • Object.entries(obj) is a convenient method for obtaining an array of a given object's own enumerable property [key, value] pairs.
  • It is particularly useful for scenarios where you need to access both keys and values together, making it easy to iterate through an object's properties in a structured way.
  • Understanding this method is essential for working with objects in JavaScript, especially when you want to manipulate or display the object's key-value pairs effectively.