DEV Community

Muhammad Hasnain
Muhammad Hasnain

Posted on

Easiest way to convert JavaScript object to map!

const person = {
  name: 'Hasnain',
  age: 22,
  profession: 'Web Developer',
};

const map = new Map(Object.entries(person));

console.log(map);
Enter fullscreen mode Exit fullscreen mode

When and why to use Map over Object? πŸ€”

There are a lot of excellent people like you, with tons of knowledge out there writing awesome answers! Here is an amazing stackoverflow post I found that explains just that! πŸŽ‰πŸŽŠ

You are lazy πŸ₯΄

I know you are lazy like me (every good developer should be), so I'd like to briefly describe the difference between Object and Map. With that information, be the judge of when to use which! 😎

According to Mozilla:

  1. A Map's key can be any value, including primitive types, objects and functions.
  2. You can use for...of loop to iterate Map in the insertion order, meaning what you first inserted will be the first element to show up in the loop and so on.
  3. Just as Array have length property, Map comes with a size property.
  4. Performs better when a lot of insertion and removal operations are involved.

Top comments (3)

Collapse
 
calag4n profile image
calag4n

Do you know some use cases in which functions as keys of a Map would be relevant ?

Collapse
 
hasnaindev profile image
Muhammad Hasnain • Edited

Doing that is less useful compared to passing objects as keys but not useless. Here is the best example I could come up with.

const map = new Map();

function computeOrGetValueFromCache(callback) {
  if (map.has(callback)) return map.get(callback);
  const value = callback();
  map.set(callback, value);
  return value;
}

const processedThumbnail = computeOrGetValueFromCache(processImage(thumbnail));
Enter fullscreen mode Exit fullscreen mode

Here we just implemented a caching system where a function that does some heavy computation runs only once and we don't have to worry about giving them clever and unique keys.

Also, keep in mind that in JavaScript, functions are objects! You can even use Function constructor to instantiate functions. Probably, that's why you can pass functions as keys to Map.

Collapse
 
calag4n profile image
calag4n

Oh, ok I got it .
Thanks for the example, it's helpful. πŸ‘