Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string to map object in javascript

Tags:

javascript

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.

like image 519
VAMSEE MOHAN KRISHNA Avatar asked Dec 07 '22 17:12

VAMSEE MOHAN KRISHNA


2 Answers

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.

like image 52
Koushik Chatterjee Avatar answered Dec 10 '22 06:12

Koushik Chatterjee


That's because the map.toString() prints [object Map] which is not parsable by JSON.parse

You should use JSON.stringify to achieve your objective

Corrected script

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

console.log(map);
//since the underlying type is array requires to be expanded [...map]
console.log(JSON.stringify([...map])); 

map2 = new Map(JSON.parse(JSON.stringify([...map])));

Remember: Maps are immutable objects, and the underlying type is an array, you have to reassign the map variable or chain the sets functions.

Full explanation can be found here: http://2ality.com/2015/08/es6-map-json.html

like image 21
saniales Avatar answered Dec 10 '22 07:12

saniales