JavaScript Object entries() | Method

  • by

Using JavaScript Object entries(), you can array key-value pairs of objects with enumerable properties. The ordering of the properties is the same as that given by looping over the property values of the object manually.

Object.entries(obj)

Example JavaScript Object entries()

Simple example code returns arrays of the given object’s own enumerable string-keyed property [key, value] pairs.

<!DOCTYPE html>
<html>
<body>

<script>
   const obj = { 10: 'Apple', 21: 'Cherry', 23: 'Mango' };  
  
   console.log(Object.entries(obj));  

 </script>

</body>
</html> 

Output:

JavaScript Object entries() Method

More examples

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

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

// random key ordering
const obj2 = { 42: "a", 22: "b", 71: "c" };

console.log(Object.entries(obj2));

// string -> from ES2015+, non objects are coerced to object
const string = "code";
console.log(Object.entries(string)); 

// 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

The main difference between the Object.entries() and the for...in loop is that the for...in loop also enumerates object properties in the prototype chain.

Do comment if you have any doubts or suggestions on this JS object topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Tags:

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.