Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
65
rated 0 times [  70] [ 5]  / answers: 1 / hits: 38951  / 7 Years ago, wed, august 30, 2017, 12:00:00



var map = new Map();
map.set('key1','value1');
map.set('key2','value2');

console.log(map);
console.log(map.toString());
console.log(JSON.parse(map.toString()))
//Uncaught SyntaxError: Unexpected token o in JSON at position 1





Converted map object to string using toString() and now I am unable to convert to map object from string.


More From » javascript

 Answers
13

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.


[#56625] Saturday, August 26, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
cody

Total Points: 679
Total Questions: 111
Total Answers: 111

Location: Czech Republic
Member since Thu, Aug 11, 2022
2 Years ago
;