Object.entries() In JavaScript

Object.entries() In JavaScript | JavaScript objects are used to store collections of data, and their entries refer to the properties or keys of an object. The Object.entries() method in JavaScript is used to return an array of a given object’s own enumerable property [key, value] pairs. In other words, it converts an object into an array of key-value pairs.

One of the benefits of using Object.entries() is that it makes it easy to iterate over an object’s properties. It’s a convenient way to access and manipulate the properties of an object. Additionally, it can be used to perform operations such as sorting or filtering, which are not possible with a standard object. Here is an example of how to use Object.entries():-

let obj = { name: "John", age: 30 };
let entries = Object.entries(obj);
console.log(entries);

Output:-

[ [ ‘name’, ‘John’ ], [ ‘age’, 30 ] ]

In the example above, the Object.entries() method is used to convert the object “obj” into an array of key-value pairs. The result is a two-dimensional array, where each sub-array contains a key and its corresponding value. Also see:- Check If Key Is In Object In JavaScript

Another use case for Object.entries() is to convert an object into a Map. Maps are similar to objects in that they store key-value pairs, but they have some advantages over objects, such as being iterable and providing a clear size property. To convert an object into a Map, you can use the following code:-

let obj = { name: "John", age: 30, gender: "Male" };
let map = new Map(Object.entries(obj));
console.log(map);

Output:-

Map(3) { ‘name’ => ‘John’, ‘age’ => 30, ‘gender’ => ‘Male’ }

In the example above, the Object.entries() method is used to convert the object “obj” into an array of key-value pairs, which is then passed to the Map constructor to create a Map.

It’s worth noting that the Object.entries() method only returns the enumerable properties of an object. Enumerable properties are those that can be looped over, such as for…in or Object.keys(). Non-enumerable properties, on the other hand, are hidden and cannot be looped over. To get both enumerable and non-enumerable properties, you can use the Reflect.ownKeys() method.

In conclusion, the Object.entries() method in JavaScript provides a convenient way to access and manipulate the properties of an object. By converting an object into an array of key-value pairs, it makes it easier to perform operations such as iteration and sorting. Whether you need to convert an object into a Map or simply access its properties, Object.entries() is a useful tool to have in your JavaScript arsenal.

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *