Moving from Javascript Object to Maps
Tags: javascript, codenewbie, tutorial, codequality
Published: 2020-10-19 12:24:35


A few days back, a colleague of mine shared [this post](https://medium.com/better-programming/stop-using-objects-as-hash-maps-in-javascript-9a272e85f6a8) 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.

```js
const map = new Map();
```

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

```js
// 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
```

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.

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

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

map.has("non-existing-key"); // false
```

### 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.

```js
map.clear();
```

## 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.

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

// size of maps
const map = new Map();
const sizeOfMap = map.size; // 0
```

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

```js
// 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}
```

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.

```js
// Just use Array.from function
Array.from(map.keys()); ["test"]
```

## 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.

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

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

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](https://www.npmjs.com/package/convert-to-map).

---

For more, you can follow me on [Twitter](https://twitter.com/hi_iam_chris_), [LinkedIn](https://www.linkedin.com/in/kpajtasev/), [GitHub](https://github.com/kristijan-pajtasev/), or [Instagram](https://www.instagram.com/hi_iam_chris_/).