DEV Community

Cover image for JavaScript Map
Bello Osagie
Bello Osagie

Posted on β€’ Edited on

2 1

JavaScript Map

A map is a collection of keyed data items.

The common methods and properties are shown below:

  • new Map() – creates a map.
  • map.set(key, value) – stores the value by the key.
  • map.get(key) – returns the value by the key, undefined otherwise.
  • map.has(key) – returns true if the key exists, false otherwise.
  • map.delete(key) – removes the value by the key.
  • map.clear() – removes everything from the map.
  • map.size – returns the current element count.

Map keys data types

Map keys are in any data type - string number boolean bigint object undefined NaN etc.

See the example below:

const map = new Map();

map.set('4', 'str'); // key in string data type
map.set(4, 'num'); // key in number data type
map.set(true, 'bool'); // key in boolean data type

console.log( map.get(4) ); // num
console.log( map.get('4') ); // str

console.log( map.size ); // 3
Enter fullscreen mode Exit fullscreen mode

Objects as keys in maps

Keys in a map can also be objects.

See the example below:

const obj = { name: "Bello" };

const map= new Map();

map.set(obj, 69);

console.log( map.get(obj) ); // 69
Enter fullscreen mode Exit fullscreen mode

Map uses the algorithm SameValueZero to test keys for equivalence.


Chaining

We can set keys of corresponding values of a map by chaining.

See the example below:

const map = new Map();

map.set('4', 'str'); // key in string data type
map.set(4, 'num'); // key in number data type
map.set(true, 'bool'); // key in boolean data type

console.log( map.get(4) ); // num
console.log( map.get('4') ); // str

console.log( map.size ); // 3
Enter fullscreen mode Exit fullscreen mode

In the example above, we can instead chain the calls before getting the corresponding key values.

See the example below:

const map = new Map();

map.set('4', 'str')
  .set(4, 'num')
  .set(true, 'bool');

console.log( map.get(4) ); // num
console.log( map.get('4') ); // str

console.log( map.size ); // 3
Enter fullscreen mode Exit fullscreen mode

Iteration over Map

There are 3 methods to loop over a map.

  • map.keys() - returns an iterable for keys,
  • map.values() - returns an iterable for values,
  • map.entries() - returns an iterable for entries

See the example below:

const fruitsAmount = new Map([
  ['Apple', 2],
  ['tomatoes', 5],
  ['onion',    10]
]);

// iterate over keys (fruit)
for (let fruit of fruitsAmount.keys()) {
  console.log(fruit); 
/*
Apple
tomatoes
onion
*/
}

// iterate over values (amounts)
for (let amount of fruitsAmount.values()) {
  console.log(amount); 
/*
2
5
10
*/
}
Enter fullscreen mode Exit fullscreen mode

forEach

Just like we can use forEach on objects like an array, it can also be used on maps.

See the example below:

const fruitsAmount = new Map([
  ['Apple', 2],
  ['tomatoes', 5],
  ['onion',    10]
]);

// iterate over keys (fruit)
fruitsAmount.forEach( (value, key, map) => {
  console.log(`${key}: ${value}`); 

/* 
Apple: 2
tomatoes: 5
onion: 10
*/

});
Enter fullscreen mode Exit fullscreen mode

Map from Object and Object from Map

Object.entries - Map from Object

A map is created by passing an iterable object into it as an array. For example, the iterable array can contain as many entries as [ key, value ] for initialization.

See the example below:

const fruitsAmount = new Map([
  ['Apple', 2],
  ['Tomatoes', 5],
  ['Onion',    10]
]);

console.log( map.get('Apple') ); // 2
Enter fullscreen mode Exit fullscreen mode

We can have a map from an Object by using the built-in method Object.entries

The syntax is:

Object.entries(obj)
Enter fullscreen mode Exit fullscreen mode

See the example below:

const fruitsAmount = {
  Apple: 2,
  Tomatoes: 5,
  Onion: 10,
};

let map = new Map(Object.entries(obj));

console.log( map.get('Apple') ); // 2
Enter fullscreen mode Exit fullscreen mode

Object.fromEntries - Object from Map

The Object.fromEntries does the reverse shown above. Array entries of [ key, value ] pairs create an object.

See the example below:

const fruitsAmount = Object.fromEntries([
  ['Apple', 2],
  ['Tomatoes', 5],
  ['Onions',    10]
]);

console.log(fruitsAmount); // { Apple: 2, Tomatoes: 5, Onions: 10 }

console.log(fruitsAmount.Apple); // 2
Enter fullscreen mode Exit fullscreen mode

We can create an object from a may by using the syntax below:

Object.fromEntries( map.entries() ) // ... as passed array argument
// or 
Object.fromEntries( map ) // ... as passed map argument
Enter fullscreen mode Exit fullscreen mode

Object.fromEntries only allows an iterable array or object as the argument.

See the example below:

const fruitsAmount = new Map();
fruitsAmount.set('Apple', 2);
fruitsAmount.set('Tomatoes', 5);
fruitsAmount.set('Onions', 10);

const obj = Object.fromEntries( fruitsAmount.entries() ); 
// const obj = Object.fromEntries(fruitsAmount); 

console.log(obj); // { Apple: 2, Tomatoes: 5, Onions: 10 }

console.log(obj.Apple); // 2
Enter fullscreen mode Exit fullscreen mode

Buy me a Coffee


Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (0)

Qodo Takeover

Introducing Qodo Gen 1.0: Transform Your Workflow with Agentic AI

Rather than just generating snippets, our agents understand your entire project context, can make decisions, use tools, and carry out tasks autonomously.

Read full post

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay