且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

用于在javascript中映射对象的字符串

更新时间:2023-11-05 11:25:40

要存储字符串化结果,***使用普通JSON对象,但是使用 Map ,您可以创建一个条目数组并将其字符串化

  var str = JSON.stringify(Array.from(map.entries())); 

然后你可以再次将JSON字符串解析为数组并构造一个新的地图

  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()) ); //将字符串存储在某个地方或将其传递给某人//或者你想要携带它//重新构造地图againvar map2 = new Map(JSON.parse(str))console.log('key1',map2 .get('key1')); console.log('key2',map2.get('key2'));  



然而, Array.from(map),或者使用也会返回相同的东西,可以在这里使用,但是有人不能承认这是什么原因lly返回直到执行它,另一方面,获取Iterator然后形成一个数组更传统和可读,但Array.from(map)可能是一个更好的解决方案。另外点差运营商可用于地图 [...地图] map.entries() [... map.entries()] 以形成相同的条目数组。


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.

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.