JavaScript Map
Tags: javascript, tutorial, webdev, codenewbie
Published: 2021-03-05 13:54:03

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:

```js
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
```

---
### Objects as keys in maps
Keys in a map can also be objects.

See the example below:

```js
const obj = { name: "Bello" };

const map= new Map();

map.set(obj, 69);

console.log( map.get(obj) ); // 69
```

> `Map` uses the algorithm [SameValueZero](https://tc39.github.io/ecma262/#sec-samevaluezero) to test keys for equivalence.

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

See the example below:

```js
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
```

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

See the example below:

```js
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
```

---
### 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:

```js
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
*/
}
```

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

See the example below:

```js
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
*/

});
```

---
### 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:

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

console.log( map.get('Apple') ); // 2
```

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

The syntax is:

```
Object.entries(obj)
```

See the example below:

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

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

console.log( map.get('Apple') ); // 2
```

#### *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:

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

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

console.log(fruitsAmount.Apple); // 2
```

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
```

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

See the example below:

```js
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
```

---
[![Buy me a Coffee](https://res.cloudinary.com/bizstak/image/upload/v1610317510/ko-fi-trans_fr3su4.png)](https://www.buymeacoffee.com/techstackmedia)

---