Some of the terms used in this article explain: any type map: The key of the map object can be any JavaScript type; string Map:map object's key is JavaScript string; Two-value pairs: An array object with and only two elements, such as [true,7]; Two-value pair array: An array object with each element being a two-value pair. converting an array with two values to any type of map and JSON transformation between Map and two-valued pairs of array
Use spread operator to turn the Map into a two-value pair array:
> Let Mymap = new Map (). Set (True, 7). Set ({foo:3}, [' abc ']);
Undefined
> [... mymap]
[[True, 7], [{foo:3}, [' ABC ']]]
>
Turns a binary pair array into a MAP:
> New Map ([[True, 7], [{foo:3}, [' abc ']])
Map {true => 7, Object {foo:3} => [' abc ']}
transformation between a Map and a JSON string
Tool Method:
function Maptojson (map) {return
json.stringify ([.... map]);
}
function Jsontomap (jsonstr) {return
new Map (Json.parse (JSONSTR));
}
Demonstrate:
> Let Mymap = new Map (). Set (True, 7). Set ({foo:3}, [' abc ']);
Undefined
> Maptojson (mymap)
' [true,7],[{"foo": 3},["abc"]]] '
> Jsontomap (' [true,7],[{' foo ': 3 },["abc"] "]"
Map {true => 7, {foo:3} => [' abc ']}
converting between String Map and JSON using Object
conversion between String Map and Object
Tool Method:
function Strmaptoobj (strmap) {let
obj = Object.create (null);
for (let [k,v] of Strmap) {
obj[k] = v;
}
return obj;
}
function Objtostrmap (obj) {let
strmap = new Map ();
for (Let K. Object.keys (obj)) {
strmap.set (k, obj[k]);
return strmap;
}
Example Demo:
> Let Mymap = new Map (). Set (' Yes ', true). Set (' No ', false);
> Strmaptoobj (mymap)
{yes:true, no:false}
> Objtostrmap ({yes:true, no:false})
[[' Yes ', true], [ ' No ', false]]
conversion between string Map and JSON strings
Tool Method:
function Strmaptojson (strmap) {return
json.stringify (Strmaptoobj (Strmap));
}
function Jsontostrmap (jsonstr) {return
Objtostrmap (Json.parse (JSONSTR));
}
Example Demo:
> Let Mymap = new Map (). Set (' Yes ', true). Set (' No ', false);
> Strmaptojson (mymap)
' {yes ': true, ' no ': false} '
> Jsontostrmap (' {' Yes ': true, ' no ': false} ');
Map {' Yes ' => true, ' no ' => false}
Reference Articles
Converting ES6 Maps to and from JSON
This paper is mainly based on the translation of the text.