How to Iterate Over JavaScript Object Entries


This post includes different ways for iterating over JavaScript Object entries and a performance comparison of those techniques.

Technique 1 : Object.entries

Object.entries() returns an iterable list of key, value pairs. This list counts only enumerable properties and doesn't include properties from prototype chain.

What are Enumerable Properties?
Properties created via simple assignment or via a property initializer

Technique 2 : Object.keys

Object.keys() returns an array of object keys. However, this function returns only enumerable properties.

Technique 3 : Object.values

Object.values() returns an array of object property values. This function returns values of enumerable properties only.

Technique 4 : for...in loop

for...in loop can be used to iterate over enumerable properties of JavaScript objects. This loop includes inherited properties from prototype chain.

Technique 5 : Object.getOwnPropertyNames

Object.getOwnPropertyNames returns all the properties of an object including non enumerable properties. The result set will also include properties inherited from prototype chain.

Performance Comparison

In order to compare the performance of each of above techniques, following script was executed for 1000 objects having 1 million properties in each.

Results

Rank Technique Time(ms)
1 for...in loop 475115.36589
2 Object.keys() 529389.1190520001
3 Object.getOwnPropertyNames() 896195.1831180009
4 Object.values() 1010445.4276509999
5 Object.entries() 1796605.2712070015

Chart below gives a better comparison overview of the techniques.

Based on above results, the winner or the fastest technique to iterate over Javascript Object entries is for...in.

Comments

  1. This comment has been removed by a blog administrator.

    ReplyDelete
  2. This comment has been removed by a blog administrator.

    ReplyDelete
  3. Hello. Thank you for the good content.
    I am a developer in Korea. Can I translate and post this posting?

    ReplyDelete

Post a Comment