How to map object in JavaScript

Often lookup tables/hash maps are implemented as objects in JavaScript. But the Map object is better since it is more specialized:

  • Maps are not inherited from Object, so there are no default keys to accidentally override.
  • It has a size property. Objects keys must be manually counted to get the size.
  • The map key can be any value including an object (object keys auto-convert to strings)

Comparisons are done using ===, so using non-primitive values is not very useful since the original object would have to be used. Though not converting every key to a string does have advantages. For example, this simulates adding to a map over time which a sort by date:

Notice how a normal forEach loop can be added. The loop is also gauranteed to happen in order of insertion while object property iteration order varies per environment. Doing this with an object based hash map would require a strategy like saving each data as a string of its timestamp (making the keys less readable). Then extracting and converting them which is a cumbersome process.

What do you think?

5 points

Total votes: 0

Upvotes: 0

Upvotes percentage: 0.000000%

Downvotes: 0

Downvotes percentage: 0.000000%

Written by TimeOdd

TimeOdd is a leading technology media property, dedicated to obsessively profiling startups, reviewing new Internet products, and breaking tech news.



TimeOdd Stories - Peanut Chicken

West African Spicy Peanut Chicken Wings – A West African specialty

TimeOdd Stories - Snoring

Are you sick of snoring- find the secret