Javascript Object.entries()

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

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 string-keyed property key and value pairs are to be returned.

Return value from entries()

  • Returns array of the given object's own enumerable string-keyed property [key, value] pairs.

Note: The ordering of the properties is the same as that when looping over them manually using for...in loop.


Example: Using Object.entries()

const obj = { name: "Adam", age: 20, location: "Nepal" };
console.log(Object.entries(obj)); // [ [ 'name', 'Adam' ], [ 'age', 20 ], [ 'location', 'Nepal' ] ]

// Array-like objects
const obj1 = { 0: "A", 1: "B", 2: "C" };
console.log(Object.entries(obj1)); // [ [ '0', 'A' ], [ '1', 'B' ], [ '2', 'C' ] ]

// random key ordering
const obj2 = { 42: "a", 22: "b", 71: "c" };
// [ [ '22', 'b' ], [ '42', 'a' ], [ '71', 'c' ] ] -> arranged in numerical order of keys
console.log(Object.entries(obj2));

// string -> from ES2015+, non objects are coerced to object
const string = "code";
console.log(Object.entries(string)); // [ [ '0', 'c' ], [ '1', 'o' ], [ '2', 'd' ], [ '3', 'e' ] ]

// primite types have no properties
console.log(Object.entries(55)); // []

// Iterating through key-value of objects
for (const [key, value] of Object.entries(obj)) {
  console.log(`${key}: ${value}`);
}

Output

[ [ 'name', 'Adam' ], [ 'age', 20 ], [ 'location', 'Nepal' ] ]
[ [ '0', 'A' ], [ '1', 'B' ], [ '2', 'C' ] ]
[ [ '22', 'b' ], [ '42', 'a' ], [ '71', 'c' ] ]
[ [ '0', 'c' ], [ '1', 'o' ], [ '2', 'd' ], [ '3', 'e' ] ]
[]
name: Adam
age: 20
location: Nepal

Recommended Reading: Javascript Object.keys()

Did you find this article helpful?