DEV Community

Cover image for Moving from Javascript Object to Maps
Kristijan Pajtasev
Kristijan Pajtasev

Posted on • Edited on

Moving from Javascript Object to Maps

A few days back, a colleague of mine shared this post about JavaScript maps and the benefits of their usage. The map is a newer feature of JavaScript. It is only available since ES6. So no wonder it is not as popular feature as it probably should be. Then again, just using an ordinary object might seem more comfortable to use than a map. That is the reason for this post. I am not covering why you should use maps. But it is a cheat sheet on how to use them.

Basics

If you want to replace JavaScript objects with maps, you want them to support the same primary functions. And they do, just slightly different. The following examples demonstrate how to create a map, insert an item, get it, and remove it from the map.

Creating a map

A map is an object; therefore, you need to use a new keyword to create it.

const map = new Map();
Enter fullscreen mode Exit fullscreen mode

Using map

Once you create it, you can use a list of different functions that it provides.

// insert into map
map.set("key", "value");

// get value from map
map.get("key"); //value

// get value for non-existing key
map.get("non-existing-key"); // undefined

// remove item from map
map.delete("key"); // true
Enter fullscreen mode Exit fullscreen mode

I think all three functions are self-explanatory, so I won't go into explaining them. But I do want to mention two things. The first one is setting items. If there is already a value with the same key, there is no error or warning. The result is the only new value. The second thing is deleting. If you try to remove a non-existing key, the returned value is false. Otherwise true. A deleting method returns a boolean value indicating if removal was successful.

Other useful functions

There is a whole set of useful functions that make working with maps easier than objects.

Containing element

Checking the existence of value in JavaScript objects can be difficult. You can do it by checking the value for that key. But that won't work if that value is undefined. There is still a key, but the value is undefined. The Map object has a particular function for that.

// insert into map
map.set("key", "value");

// check if key exists
map.has("key"); // true

map.has("non-existing-key"); // false
Enter fullscreen mode Exit fullscreen mode

Removing all values

Using the delete function removes one item from it. But you can't run it for every key if you want to empty the map. That is why there is a clear function.

map.clear();
Enter fullscreen mode Exit fullscreen mode

Number of items in a map

With regular JavaScript objects, checking if it is empty is messy. First, you use the keys function of Object to get the list of them. Then you need to check the number of those keys. With maps, it is one property, size.

// size of objects
const obj = {}
const sizeOfObj = Object.keys(obj).length; // 0

// size of maps
const map = new Map();
const sizeOfMap = map.size; // 0
Enter fullscreen mode Exit fullscreen mode

Other object functions

As seen in the previous example, you can use Object functions on JavaScript objects. The map supports them natively.

// old way
const obj = { test: 123 }
Object.keys(obj); // ["test"]
Object.values(obj); // [123]
Object.entries(obj); // [["test", 123]]


// new Map object
const map = new Map();
map.set("test", 123);
map.keys(); // MapIterator {"test"}
map.values(); // MapIterator {123}
map.entries(); // MapIterator {"test" => 123}
Enter fullscreen mode Exit fullscreen mode

You might notice that for the map, results are all instances of MapIterator. It sadly means you can't use array functions on them(map, filter, forEach, reduce). What you can use is the for..of loop. But the good news is there is a simple way to get it as an array.

// Just use Array.from function
Array.from(map.keys()); ["test"]
Enter fullscreen mode Exit fullscreen mode

Creating Map from JSON

If you are using JavaScript, there is a high chance you are interacting with some server. In that case, the server probably returns you JSON. So the question is how to convert it to a map? If you have one level of depth, the following example is the simplest way. If the depth level is higher than one, you would need to convert each value to the map first.

const obj = {
    firstName: "john",
    lastName: "doe"
};

const asMap = new Map(Object.entries(obj)); // Map(2) {"firstName" => "john", "lastName" => "doe"}
Enter fullscreen mode Exit fullscreen mode

As mentioned above, this one line is working only for the depth level of the object is one. If any value in it is an object, you need to convert it individually. But for that, you can also use this converter-to-map NPM package.


For more, you can follow me on Twitter, LinkedIn, GitHub, or Instagram.

Top comments (0)