How to create a Javascript Map from an Array or an Object and vice versa
Photo: Alex Andrews/Pexels
Introduction
In our previous articles on Map, we learned how to create a Map and use its properties and methods and iterate over it. In this article, we will learn how we can convert a Map to array and object and vice versa. Let's get started.
Creating a Map using Array
Let's create a Map using the new keyword and put elements in it using the map.set()
method.
Instead of adding elements using map.set()
, we can pass an array of key-value pairs to initialize a Map.
Creating an Array from Map
To create an Array from Map, we can use map.entries()
and Array.from()
method.
We can also pass a Map directly to Array.from() as Map returns an iterable of [key,value]
pairs by default.
To get an array of Map keys and values, we can use the same approach as above.
Creating a Map from an Object
To create a Map from Object, we can convert an object into an array of [key, value]
pairs
and then create a Map using it.
To get an array of key-value pairs from the above object, we will use Object.entries()
.
Creating an Object from a Map
If we want to convert the Map in our previous example, back to Object it was created from - obj,
we can use Object.fromEntries()
method.
We can pass the Map directly to Object.fromEntries()
and we will get the same result Map returns an
iterable of [key, value]
pairs by default.
Summary
In this article, we learned:
- How to create a Map using the
new
keyword and using a[key, value]
array. - How to get a
[key, value]
2d array from a Map. - How to create a Map from a plain Javascript Object.
- How to create a plain javascript Object from a Map.