1console.log("hello-world);
javascript
console.log("hello-world);
hidden codeblock for CSS
css
.container {
  width: 80%;
}
hidden codeblock for CSS
html
<pre><code class="language-css">
.container {
  width: 80%;
}
</code></pre>
hidden codeblock for CSS
1console.log("hello-world);
javascript
console.log("hello-world);
hidden codeblock for CSS
css
.container {
  width: 80%;
}
hidden codeblock for CSS
html
<pre><code class="language-css">
.container {
  width: 80%;
}
</code></pre>
hidden codeblock for CSS

How to Initialize a Map with Values in JavaScript

ReadTime: 4 minutes

Mastering Map initialization is a pivotal skill for effective data handling. This blog shows various techniques, from arrays to objects, manual additions to replications, providing a comprehensive guide to empower your coding journey. Let’s dive in!


Initialize a Map with Values from an Array

Initialize your Map with values from an array passed as Map constructor argument.

javascript
const map1 = new Map([
  ['city', 'New York'],
  ['population', 8500000],
]);

// Result: Map(2) { 'city' => 'New York', 'population' => 8500000 }
console.log(map1);
console.log(map1.get('city')); // πŸ‘‰οΈ New York
Initialize a Map with values from an array

Insights:

  • The two-dimensional array in the Map() constructor defines key-value pairs. Inside each nested array, first element is key, second is value.

  • Utilize Map.get() to retrieve individual values.


Initialize a Map with Values from an Object

Smoothly transition from objects to maps using the Object.entries() method.

javascript
const obj = {city: 'New York', population: 8500000};

const map1 = new Map(Object.entries(obj));

// Result: Map(2) { 'city' => 'New York', 'population' => 8500000 }
console.log(map1);
Initialize a Map with values from an object

Insights:

  • Object.entries(obj) transforms an object into a two-dimensional array, where each nested array contains a key and a value. This can be used to initialize Map.
  • Tip: Familiarize yourself with output of Object.entries();

Manually Adding Values to a Map Object

Dynamically setting key-value pairs using the Map.set() method.

javascript
const map1 = new Map();

map1
  .set('city', 'New York')
  .set('population', 8500000)
  .set('famousFor', 'Broadway');

// Result: Map(3) { 'city' => 'New York', 'population' => 8500000, 'famousFor' => 'Broadway' }
console.log(map1);
Manually adding values to a Map object

Insights:

  • Use Map.set() for efficient addition of key-value pairs.
  • Tip: Leverage method chaining for concise Map building. Otherwise you can add three times separately on map1 too.

Initialize a Map with Values from Another Map

Efficiently replicate a Map’s content by initializing a new Map with values from an existing one.

javascript
const map1 = new Map();

map1.set('city', 'New York');
map1.set('population', 8500000);
map1.set('famousFor', 'Broadway');

const map2 = new Map(map1);

// Result: Map(3) { 'city' => 'New York', 'population' => 8500000, 'famousFor' => 'Broadway' }
console.log(map2);
Initialize a Map with values from another Map

Insights:

  • Directly pass one Map object to the Map() constructor for streamlined initialization.

  • Observe the seamless replication of key-value pairs from the source Map to the new Map.


Test Your Understanding:

Now, let’s solidify your understanding with a practice coding question.

You are working on a project that involves storing information about various cities. Design a JavaScript function initializeCityMap that takes an array of city objects and returns a Map containing the city names as keys and their respective populations as values.

Problem (JavaScript)

javascript
function initializeCityMap(cityData) {
  // < < < πŸ‘‰ You code here πŸ‘ˆ > > >
}

// Example Usage:
const citiesData = [
  { name: 'New York', population: 8500000 },
  { name: 'Tokyo', population: 13929286 },
  { name: 'London', population: 8908081 },
];

const cityMap = initializeCityMap(citiesData);
console.log(cityMap);

/*
Expected output of your initializeCityMap function:

Map(3) {
  'New York' => 8500000,
  'Tokyo' => 13929286,
  'London' => 8908081
}
*/
Problem Code

Please attempt before seeing the Answer:

Solution Code
javascript
function initializeCityMap(cityData) {
  const cityMap = new Map();

  cityData.forEach(city => {
      cityMap.set(city.name, city.population);
  });

  return cityMap;
}
Solution Code

Conclusion:

Whether you opt for array-based initialization, object transformation, manual additions, or replication from another Map, each method serves a specific purpose. Choosing the right technique depends on the context of your project, providing versatility in your coding arsenal.

Contact

Feel free to reach out!