JavaScript Object.entries()

The Object.entries() method returns an array of key-value pairs of an object's enumerable properties.

Example


entries() Syntax

The syntax of the entries() method is:

Object.entries(obj)

The entries() method, being a static method, is called using the Object class name.


entries() Parameters

The entries() method takes in:

  • obj - the object whose enumerable properties are to be returned.

entries() Return Value

The entries() method returns an array of all the enumerable properties of an object, where each element will be a key-value pair.


Example 1: JavaScript Object.entries()

In the above example, we have created an object named student. Then, we used the entries() method to get its enumerable properties in key-value format.

Note: Enumerable properties are those properties that are visible in for...in loops and with Object.keys().


Example 2: entries() With Randomly Arranged Keys

In the above example, we have created an object obj whose keys are arranged randomly i.e. they have no order (ascending or descending).

However, if we use the entries() method on obj, the output will include key-value pairs where the keys are sorted in ascending order.


Example 3: entries() to Iterate Through Key-Value Pairs

Output

name: John
age: 27
location: Nepal

In the above example, we have used the entries() method inside a for loop to iterate through the obj object.

In each iteration of the loop, we can access the current object property in the form of key-value pairs.


Example 4: entries() With Strings

In the above example, we have used the entries() method with the str string. Here, each element of the output includes:

  • key - the index of each character in the string
  • value - individual character in the corresponding index

Recommended Reading: