VOOZH about

URL: https://www.geeksforgeeks.org/javascript/javascript-object-entries-method/

⇱ JavaScript Object entries() Method - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

JavaScript Object entries() Method

Last Updated : 18 Sep, 2024

The Object.entries() method in JavaScript is used to retrieve an array of an object's enumerable property [key, value] pairs. This method is particularly useful for transforming and iterating over objects in situations where array-like manipulation is needed.

Syntax:

Object.entries(obj);

Parameters:

  • obj: It is the object whose enumerable property [key, value] pairs are to be returned.

Return Value:

Object.entries() returns an array consisting of enumerable property [key, value] pairs of the object passed.

Key Characteristics

  • The order of the properties returned by Object.entries() is the same as the order provided by manually iterating over the properties of the object.
  • It only returns enumerable properties that belong to the object directly (not inherited from its prototype chain).

Examples of JavaScript Object entries() Method

Example 1: In this example, an object "obj" has been created with three property[key, value] pairs, and the Object.entries() method is used to return the first property [key, value] pair of the object.


Output
[ '1', 'billy' ]

Example 2: In this example, an object "obj" has been created with three property[key, value] pairs, and the Object.entries() method is used to return all the property [key, value] pairs of the object. 


Output
[ [ '10', 'adam' ], [ '35', 'chris' ], [ '200', 'billy' ] ]

Applications of Object.entries()

Iterating over Objects:

You can easily iterate over the object’s properties by using Object.entries() in combination with array methods like forEach() or map().


Output
name: Alice
age: 25
city: New York

Converting Objects to Arrays:

Since Object.entries() returns an array of arrays, it is useful for converting objects into arrays, especially when you need to work with array-specific functions.


Output
[ [ 'name', 'Alice' ], [ 'age', 25 ], [ 'city', 'New York' ] ]

Transforming Objects:

You can use Object.entries() to manipulate or transform an object, such as changing its structure or reformatting it.


Output
[ [ 'NAME', 'Alice' ], [ 'AGE', 25 ], [ 'CITY', 'New York' ] ]

Handling Arrays:

Since arrays are objects in JavaScript, Object.entries() can be applied to arrays to get index-value pairs.


Output
[ [ '0', 'Apple' ], [ '1', 'Banana' ], [ '2', 'Cherry' ] ]

Handling Non-Enumerable Properties

The Object.entries() method only includes enumerable properties in the returned array. Non-enumerable properties (properties defined with Object.defineProperty() and the enumerable: false option) will not be included.


Output
[ [ 'name', 'Alice' ] ]

Supported Browsers:

  • Chrome
  • Edge
  • Firefox
  • Opera
  • Safari
Comment