How to add Key/Value pairs to a Map in JavaScript


In this blog you will understand how to efficiently add key/value pairs to a Javascript Map, common errors, and a fun coding problem to polish your skills.


Refresher: Js Map and Map vs Object

Before diving into the methods, let’s briefly recap what Maps are in JavaScript. Maps are collections that store key-value pairs. They stand out for following:

  • Any Value as a Key: Unlike objects, which typically use strings as keys, Maps can use any data type, including objects, functions, arrays.
  • Order of Elements: Maps maintain the insertion order of elements, which can be crucial for certain algorithms. In contrast, Objects don’t maintain insertion order.
  • Size Property: Easily determine the number of key/value pairs in a Map using the size property.

Methods to Add Key/Value Pairs in Maps

Using Map.Set() to a pair in JS Map

The set() method is your primary tool for inserting or modifying key-value pairs in a Map.

Adding new Key value pairs in Js Map

JavaScript
const map1 = new Map();

map1.set('username', 'alexdoe');
map1.set('age', 25);

console.log(map1); // Map(2) {'username' => 'alexdoe', 'age' => 25}
console.log(map1.get('username')); // Outputs: alexdoe

Modifying existing values in JS Map:

JavaScript
const map1 = new Map();

map1.set('username', 'alexdoe');
map1.set('age', 25);

// Modifying the username now:
map1.set('username', 'janesmith');
console.log(map1.get('username')); // Outputs: janesmith

Initializing Maps with Predefined Pairs

Maps can be initialized with an array of arrays, each representing a key-value pair. We can pass them in Map constructor itself.

JavaScript
const map1 = new Map([
  ['username', 'alexdoe'],
  ['age', 25],
  ['country', 'USA'],
  ['city', 'New York']
]);

console.log(map1); // Map(4) {'username' => 'alexdoe', 'age' => 25, ...}

Using Object.entres() to transform an Object into a Map

To convert an object’s properties to Map key-value pairs, Object.entries() is used.

JavaScript
const user = { username: 'alexdoe', age: 25 };
const map1 = new Map(Object.entries(user));

console.log(map1); // Map(2) {'username' => 'alexdoe', 'age' => 25}

Chaining with multiple Map.set()

Chain multiple set() calls thanks to its returning the Map object.

JavaScript
const map1 = new Map();

map1
  .set('username', 'alexdoe')
  .set('score', 95)
  .set('status', 'active')
  .set('city', 'New York');

console.log(map1); // Map(4) {'username' => 'alexdoe', 'score' => 95, ...}

Using Map.has() to Conditionally Add Key/Value Pairs

To avoid overwriting existing keys, use has() before set().

JavaScript
if (!map1.has('username')) {
  map1.set('username', 'newuser');
}
console.log(map1.get('username')); // Outputs: alexdoe

Using Diverse Types as Keys

Demonstrating the flexibility of Maps with various key types (like array, or even objects).

JavaScript
const map1 = new Map();
const keyObject = { id: 1 };

map1.set(keyObject, { profile: 'Developer' });

console.log(map1.get(keyObject)); // Outputs: { profile: 'Developer' }

Tips on using Map (specially Map vs Object)

  • Maps for Dynamic Keys: Opt for Maps when dealing with changing or non-string keys. Object might not be suitable choice in such scenarios.
  • Simplicity with Keys: While you can use complex structures as keys, simpler keys often make your code clearer.
  • Functional Methods: Use methods like delete(), clear(), and has() for effective Map management.
  • Using non-unique keys: Remember, keys in Maps must be unique. If you set a key that already exists, it will overwrite the existing value.
  • Map Performance: Maps are optimized for frequent additions and removals of key-value pairs.
  • Iterating Over Maps: Use methods like map.forEach() or for…of loops to iterate over Maps.
  • Certain use cases:
    • Storing Unique Elements: Due to their key-based nature, Maps are excellent for scenarios where unique identifiers are necessary.
    • Data Caching: Maps can efficiently store and retrieve data, making them ideal for caching mechanisms.
    • Maintaining Insertion Order: When the order of elements matters, Maps are the preferred choice over objects.

🧪Practice Coding Problem: The Mischievous Map

In the spirit of Test Driven Development ( 😁), lets test our understanding by solving a problem.

You’re given a Map containing some keys and values. Your task is to add a new key/value pair to this Map. However, the twist is, if the key already exists, append the new value to the existing one with a hyphen (-) in between.

JavaScript
/**
 * Modifies the given Map by adding a new key/value pair or appending to an existing key's value.
 * 
 * @param {Map} map - The original Map.
 * @param {String} key - The key to be added or modified.
 * @param {String} value - The value to be added or appended.
 * @returns {Map} The modified Map.
 */
function modifyMap(map, key, value) {
  // > > > 👉 Write code here 👈 < < <
}

// Example usage
const myMap = new Map([['theme', 'dark'], ['language', 'JavaScript']]);
console.log("Original Map:", myMap); 
// Console log before modification

// Adding a new key/value pair
modifyMap(myMap, 'framework', 'React');
console.log("Map after adding 'framework':", myMap); 
// Should show React as value for 'framework'

// Modifying an existing key
modifyMap(myMap, 'theme', 'light');
console.log("Map after modifying 'theme':", myMap); 
// Should show 'dark-light' as value for 'theme'
Please attempt before seeing the Answer:
JavaScript
function modifyMap(map, key, value) {
  if (map.has(key)) {
    value = `${map.get(key)}-${value}`;
  }
  map.set(key, value);
  return map;
}

Explanation:

  • Initially, myMap contains two key-value pairs.
  • When modifyMap is first called with 'framework', 'React', the key 'framework' does not exist in the map, so it’s simply added.
  • The second call with 'theme', 'light' finds that 'theme' already exists, so it appends 'light' to the existing value 'dark', resulting in 'dark-light'.

May this post adds value to your javascript map handling. Keep coding! 🚀

Scroll to Top