Explanation of some terms used in this article:
- Any type of Map: means that the key of the Map object can be of any JavaScript type;
- String Map: The keys of the Map object are all JavaScript Strings;
- Binary pair: an array object with one and only two elements, such as [true,7];
- Binary pair Array: An array object, each element of which is a binary pair.
Convert between any type of Map and JSON using binary Array
Conversion between Map and Array of Binary Pairs
Use the spread operator to convert a Map to an Array of binary pairs:
> let myMap = new Map().set(true, 7).set({foo: 3}, ['abc']);
undefined
> [...myMap]
[ [ true, 7 ], [ { foo: 3 }, [ 'abc' ] ] ]
>
Convert an Array of binary pairs into a Map:
> new Map([[true, 7], [{foo: 3}, ['abc']]])
Map {true => 7, Object {foo: 3} => ['abc']}
Conversion between Map and JSON string
Tool method:
function mapToJson(map) {
return JSON.stringify([...map]);
}
function jsonToMap(jsonStr) {
return new Map(JSON.parse(jsonStr));
}
Demo:
> 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' ] }
Convert 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 of 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 String
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 article
Converting ES6 Maps to and from JSON
This article is mainly based on the translation of this article.