Map

ES6 adds a new data structure, Map, which is essentially a combination of key-value pairs, similar to traditional object literals. But unlike object literals, where keys can only be strings and are cast to strings for non-string values, Map keys can be made up of various types of values.

// Traditional object types
let xx = {name: 'xx'}
let obj = {}
obj[xx] = '123' // {[object Object]: "123"}
alert( obj["[object Object]"])/ / 123
Copy the code

In the above case, we use the traditional object processing method, we will use an object as the key of the object, and all the keys such as xx will be converted to a string on output. So we get the string key “[object object]”. This is obviously not what we want.

let xx = {name: 'xx'}
let map = new Map()
map.set(xx, 123) / / the Map (1) {{... 123}} = >
alert( map.get(xx) ) / / 123
Copy the code

The Map processing method is used to add an object as a key to a Map instance. On output, it is found that the key value is the real value of the object and is not converted to a string.

Once a Map is created, we can initialize it by passing in an array (or other iterable) with key-value pairs.

let map = new Map([['name'.'xx'],
  ['age'.23]])console.log(map) // Map(2) {"name" => "xx", "age" => 23}
Copy the code

Map properties and methods

  • New Map() — Creates a Map.
  • Map.set (key, value) – Stores values by key.
  • Map.get (key) — Returns the value by key, or undefined if no key exists in the map.
  • Map.has (key) – Returns true if key exists, false otherwise.
  • Map.delete (key) — Deletes the value of the specified key.
  • Map.clear () — Clears the map.
  • Map. size – Returns the current number of elements.

Map [key] is not the correct way to use map

Although map[key] also works, for example we could set map[key] = 23, which would treat the map as a JavaScript plain object, and therefore imply all the corresponding restrictions (no object keys, etc.). So we should use map methods: set, get, etc.

In a Map data structure, all keys must be unique. If the same key is assigned more than once, the subsequent value overrides the previous value.

let map = new Map()
map.set(1.'aa')
map.set(1.'bb')
map.get(1) // 'bb'
Copy the code

How does Map compare keys?

Map uses the SameValueZero algorithm to compare keys for equality. It’s the same thing as strictly equal ===, except NaN is treated as equal to NaN. So NaN can also be used as a key.

Chain calls

Each map.set call returns the map itself, so we can make “chained” calls:

map.set(‘name’, ‘xx1’).set(‘age’, 23)

The Map of traverse

  • Map.keys () — iterate over and return all keys,
  • Map.values () — iterate over and return all values,
  • Map.entries () — Iterate through and return all entities [key, value], for.. That’s what “of” is used by default,
  • Map.foreach (item, key) — The first argument represents the value and the second argument represents the key.
let map = new Map()
map.set('name'.'xx')
map.set('age'.23)

map.forEach((value, key) = > {
  console.log(value, key); 
  // xx name 
  // 23 age
})

for (let key of map.keys()) {
  console.log(key);
  // name
  // age
}

for (let value of map.values()) {
  console.log(value);
  // xx
  / / 23
}

for (let [key, value] of map.entries()) {
  console.log(key, value);
    // name xx
    // age 23
}

Copy the code

map.entries === map[Symbol.iterator]

Use insert order

The order of iteration is the same as the order of insertion. Unlike ordinary objects, maps retain this order.

Map conversion to other data types

Arrays are converted to maps

Arrays are converted to maps, which can be done through the Map constructor, using the new operator to generate Map instances.

let arr = [['name'.'xx'], ['age'.23]]

let map = new Map(arr)
console.log(map) // Map(2) {"name" => "xx", "age" => 23}
Copy the code

Map is converted to an array

A Map is converted to an array, which can be done by extending the operator.

let map = new Map()
map.set('name'.'xx')
map.set('age'.23)

let arr = [...map]
console.log(arr) // (2) [Array(2), Array(2)]
Copy the code

Object is converted to Map

If we wanted to create a Map from an existing plain Object, we could use the built-in object.entries (obj) method, which returns an array of key/value pairs for the Object in exactly the format required for the Map.

let obj = {
  'name': 'xx'.'age': 23
}

let map = new Map(Object.entries(obj))
console.log(map) // Map(2) {"name" => "xx", "age" => 23}
Copy the code

Map is converted to an object

We’ve just learned how to use Object.entries(obj) to create maps from ordinary objects.

The object. fromEntries method does the opposite: given an array with [key, value] key-value pairs, it creates an Object from the array.

let map = new Map()
map.set("name".'xx')
map.set("age".23)

let obj = Object.fromEntries(map)
console.log(obj) // {name: "xx", age: 23}
Copy the code

Map is converted to Json

When Map keys are all strings

When the Map keys are all strings, you can first convert the Map to an object and then call the json.stringify () function.

let map = new Map()
map.set("name".'xx').set("age".23)

let json = JSON.stringify(Object.fromEntries(map))
console.log(json) //{"name":"xx","age":23}
Copy the code

When the Map key name has a non-string

When a Map has a non-string key name, we can first convert the Map to an array and then call the json.stringify () function

let map = new Map()
map.set({fn: 'foo'}, 'xx').set(true.'abc')

let json = JSON.stringify([...map])
console.log(json) // [[{"fn":"foo"},"xx"],[true,"abc"]]
Copy the code