A Map is a data structure introduced in the ECMAScript 6 specification. This is a convenient way to store key-value pair lists, similar to dictionaries or hash tables in other programming languages.

What is a mapping

JavaScript objects, which are essentially collections of key-value pairs (Hash structures), have traditionally been limited to strings as keys. To address this problem, ECMAScript 6 introduces Map data structures.

It is a collection of key-value pairs similar to objects, but the range of “keys” is not limited to strings. Instead, all types of values (including objects) can be used as keys.

That is, the Object structure provides string-value correspondence, while the Map structure provides value-value correspondence, which is a more complete implementation of the Hash structure.

Let’s look at a simple example to understand the basic use of Map:

// Declare the map instance
const page_info = new Map(a)// Add elements to the map
page_info.set("seo", {
"keywords": "Infoq, the Map"."description":"A Map object is a simple key/value mapping where the keys and values can be any value (the original value or the value of the object)."
})
page_info.set("title"."JavaScript ES6 map mapping")
console.log(page_info)
console.log(typeof page_info) // object
Copy the code

The output is:

Map {
'seo'= > {keywords: 'infoq, Map'.description: 'A Map object is a simple key/value mapping where the key and value can be any value (the original value or the value of the object)'
},
'title'= >'javascript ES6 map mapping '
}
object
Copy the code

From the output, a Map is essentially an object.

Object is different from Map

Object and Map are similar in that a value is accessed by a key, and the key can be deleted. As can be seen, the two are very similar. The difference is as follows:

  • MapObject Unexpected keys The Map does not contain any keys by default. Contains only explicitly inserted keys.

  • An Object has a prototype, and the key names on the prototype chain may conflict with the key names you set on the Object yourself.

  • Note: Although ES5 can initially use object.create (null) to create an Object without a prototype, this usage is less common.

  • Key types A Map’s key can be of any value, including functions, objects, or any primitive type. The key of an Object must be a String or Symbol. Order of keys Keys in a Map are ordered. Thus, when iterating, a Map object returns key values in the order they were inserted.

The key of an Object is unordered

Note: Since the ECMAScript 2015 specification, objects do retain the creation order of the string and Symbol key; Therefore, iterating over an object with only string keys produces keys in insertion order.

The number of key/value pairs of an Object can be easily obtained by using the size attribute. The number of key/value pairs of an Object can only be calculated manually.

Iterating over an Object requires obtaining its keys in some way before iterating. Performance is better when key pairs are frequently added or deleted. Optimizations are not made in cases where key/value pairs are frequently added and removed.

operation

Map Common mapping methods

The Map methods are as follows:

  • The assignment set (key, value)
  • Get (key)
  • Removes the specified key name and its corresponding value delete(key)
  • Determine whether there is a has(key)
  • Get all values values()
  • Key/Value iterator entries()
  • Traverse the forEach ()
  • Clear all key/value pairs clear()

Declare and initialize

const new_map = new Map(a);console.log(new_map); // Output: Map {}
Copy the code

The assignment set

Set (key,value), which can be used to add new key/value pairs or modify key/value pairs to return the entire Map object.

const page_info = new Map(a)/ / set the value
page_info.set("seo", {
"keywords": "Infoq, the Map"."description":"A Map object is a simple key/value mapping where the keys and values can be any value (the original value or the value of the object)."
});
console.log(page_info);
page_info.set("seo"."Seo information");
console.log(page_info);
Copy the code

The above example adds values and modifies values.

Map {
'seo'= > {keywords: 'infoq, Map'.description: 'A Map object is a simple key/value mapping where the key and value can be any value (the original value or the value of the object)'}}Map { 'seo'= >'seo information' }
Copy the code

Get the key value get

Use get(key) to get the key value, or return undefined if the key->value is not present

const page_info = new Map(a); page_info.set("title"."Javascript ES6 map mapping");
const title = page_info.get("title");
const seo_info = page_info.get("seo");
console.log(title); // Javascript es6 map mapping
console.log(seo_info); //undefined
Copy the code

Delete key value delete

Map. delete(key) Deletes the key/value pairs of the specified key. The return is true for successful deletion and false for failed deletion.

const page_info = new Map(a); page_info.set("title"."Javascript ES6 map mapping");
page_info.set("author"."infoq");
console.log(page_info); // Map {'title' => 'javascript ES6 Map ', 'author' => 'infoq'}
const deleted_author = page_info.delete("author");
const deleted_seo = page_info.delete("seo");
console.log(deleted_author); // true
console.log(deleted_seo); // false
console.log(page_info); // Map {'title' => 'javascript es6 Map '}
Copy the code

Check whether the key has exists

Use map.has(key) to check whether the specified key exists.

const page_info = new Map(a); page_info.set("title"."Javascript ES6 map mapping");
console.log(page_info); // Map {'title' => 'javascript es6 Map '}
console.log(page_info.has("title")); // true
console.log(page_info.has("seo")); // false
Copy the code

Get all key values values()

const page_info = new Map(a); page_info.set("title"."Javascript ES6 map mapping");
page_info.set("author"."infoq");
console.log(page_info.values()); // [Map Iterator] {'javascript es6 Map ', 'infoq'}
Copy the code

Key/Value iterator entries()

Use map.entries() to return an Iterator containing each [key, value] array in the map object.

const page_info = new Map(a); page_info.set("title"."Javascript ES6 map mapping");
page_info.set("author"."infoq");
console.log(page_info.entries());
Copy the code
[Map Entries] {
[ 'title'.'javascript ES6 map mapping ' ],
[ 'author'.'infoq']}Copy the code

Iterate over all key values forEach(callback)

const page_info = new Map(a); page_info.set("title"."Javascript ES6 map mapping");
page_info.set("author"."infoq");
page_info.forEach((value,key) = >{
console.log(key,value);
});
Copy the code

The output is:

Title, javascript ES6 map Author, InfoQCopy the code

Clear all key values in Map mapping clear()

Use map.clear() to clear all key-value pairs of the map.

const page_info = new Map(a); page_info.set("title"."Javascript ES6 map mapping");
page_info.set("author"."infoq");
page_info.clear();
console.log(page_info); // Map {}
Copy the code

Conversion to other data structures

Map The mapping is converted to an array

The easiest way to convert a Map into an array is to use the extension operator…

const page_info = new Map(a); page_info.set("title"."Javascript ES6 map mapping");
page_info.set("author"."infoq");
console.log([...page_info]); // [['title', 'javascript ES6 map '], ['author', 'infoq']]
Copy the code

Map The mapping is converted to an object

function mapToObj(map) {
	// object.create creates an Object without a prototype chain
    const obj = Object.create(null);
    map.forEach((v, k) = > {
        obj[k] = v;
    });
    return obj;
}
const page_info = new Map(a); page_info.set("title"."Javascript ES6 map mapping");
page_info.set("author"."infoq");

console.log(mapToObj(page_info));
Copy the code

The output is object. create creates an Object with no prototype chain:

[Object: null prototype] {
title: 'javascript ES6 map mapping '.author: 'infoq'
}
Copy the code

An array is converted to a Map

Just pass the array to the Map constructor, new Map(array).

const page_info = [
["title"."Javascript ES6 map mapping"],
["author"."infoq"]].console.log(new Map(page_info)); // Map {'title' => 'javascript ES6 Map ', 'author' => 'infoq'}
Copy the code

Object to Map

To convert a Map to JSON, you first convert the Map to an object, mapToObj, and then use the json.stringify method.

function mapToObj(map) {
    const obj = Object.create(null);
    map.forEach((v, k) = > {
        obj[k] = v;
    });
    return obj;
}
function mapToJson(map) {
    return JSON.stringify(mapToObj(map));
}
const page_info = new Map(a); page_info.set("title"."Javascript ES6 map mapping");
page_info.set("author"."infoq");
console.log(mapToJson(page_info)); // {"title":"javascript es6 map ","author":"infoq"}
Copy the code