How to Initialize a Map with Values in JavaScript

avatar

Borislav Hadzhiev

Wed Oct 27 20212 min read

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 it with values.

The first element in each nested array is the key, and the second - 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 our second example, we used the Object.entries method to create a map from an object.

The Object.entries method returns a two dimensional array, where the nested arrays contain 2 elements - the key and 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 it 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 #

Join my newsletter

I'll send you 1 email a week with links to all of the articles I've written that week

Buy Me A Coffee