To store a stringified result, better to use plain JSON object, however using Map
you can create a array of entries and stringify that
var str = JSON.stringify(Array.from( map.entries()));
and then again you can parse the JSON string to array and construct a new Map
var map = new Map(JSON.parse(str))
var map1 = new Map();
map1.set('key1','value1');
map1.set('key2','value2');
var str = JSON.stringify(Array.from( map1.entries()));
//store the string somewhere or pass it to someone
//or however you want to carry it
//re construct the map again
var map2 = new Map(JSON.parse(str))
console.log('key1', map2.get('key1'));
console.log('key2', map2.get('key2'));
However, Array.from(map)
, or using will also return the same thing and can be used here, but someone cannot grantee what it's actually returns until execute it, on the other hand, getting an Iterator and then forming an array is more conventional and readable, however Array.from(map) might be a better solution. Also spread operator
can be used over map [...map]
or map.entries() [...map.entries()]
to form the same array of entries.