How to create a Javascript Map from an Array or an Object and vice versa

Srijan } Author Pic
SrijanJan 28, 2025 - JavaScript
How to create a Javascript Map from an Array or an Object and vice versa - Reacted Node

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.

1let map = new Map();
2map.set("1", "first element");
3map.set(1, "second element");
4map.set(true, "hello world");

Instead of adding elements using map.set(), we can pass an array of key-value pairs to initialize a Map.

1let map = new Map([
2 ["1", "first element"],
3 [1, "second element"],
4 [true, "hello world"],
5]);

Creating an Array from Map

To create an Array from Map, we can use map.entries() and Array.from() method.

1let newIterable = map.entries(map);
2//return iterable with [key,value] pairs
3
4let newArray = Array.from(newIterable);
5// We will get a 2D array having [key, value] pairs.

We can also pass a Map directly to Array.from() as Map returns an iterable of [key,value] pairs by default.

1let newArray = Array.from(map);
2// We will get a 2D array having [key, value] pairs.

To get an array of Map keys and values, we can use the same approach as above.

1let newKeysIterable = map.keys();
2let newValuesIterable = map.values();
3
4let keysArray = Array.from(newKeysIterable);
5let valuesArray = Array.from(newValuesIterable);

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.

1let obj = {
2 name: "reactednode",
3 type: "website",
4};

To get an array of key-value pairs from the above object, we will use Object.entries().

1let newArray = Object.entries(obj);
2
3let map = new Map(newArray);

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.

1let newArray = map.entries();
2
3let newObject = Object.fromEntries(newArray);

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.

1let newObject = Object.fromEntries(map);

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.