How to Initialize a Map with Values in JavaScript

avatar

Borislav Hadzhiev

Last updated: Jul 25, 2022

banner

Photo from Unsplash

Initialize a Map with Values in JavaScript #

To initialize a Map with values, use the Map() constructor, passing it an array containing nested arrays of key-value pairs, where the first element in the array is the key and the second - the value. Each key-value pair is added to the new Map.

index.js
// ✅ Create Map from Array const map1 = new Map([ ['country', 'Chile'], ['name', 'Tom'], ]); // 👇️ {'country' => 'Chile', 'name' => 'Tom'} console.log(map1); // ✅ Create Map from Object const obj = {name: 'Tom', country: 'Chile'}; const map2 = new Map(Object.entries(obj)); // 👇️ {'name' => 'Tom', 'country' => 'Chile'} console.log(map2);

We passed a two-dimensional array to the Map() constructor to initialize the Map with values.

The first element in each nested array is the key, and the second is the value.

Conversely, you can also convert a Map to a two-dimensional array.

index.js
const arr = Array.from(map1); // 👉️ [['country], 'Chile], ['name', 'Tom'], ['age', 30]] console.log(arr);

We used the Array.from method to convert a Map object to an array.

Map objects are iterable.

In the second example, we used the Object.entries method to create a Map from an object.

index.js
const obj = {name: 'Tom', country: 'Chile'}; const map2 = new Map(Object.entries(obj)); // 👇️ {'name' => 'Tom', 'country' => 'Chile'} console.log(map2);

The Object.entries method returns a two-dimensional array, where each nested array contains a key and a value.

index.js
const obj = {name: 'Tom', country: 'Chile'}; // 👇️ [['name', 'Tom'], ['country', 'Chile']] console.log(Object.entries(obj));

We basically end up with the same Map initialization between the first and second approaches.

An alternative approach is to create an empty Map and manually set its key-value pairs.

index.js
const map2 = new Map(); map2.set('country', 'Chile'); map2.set('name', 'Tom'); // 👇️ {'country' => 'Chile', 'name' => 'Tom'} console.log(map2);

Further Reading #

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.