用于在javascript中映射对象的字符串 [英] string to map object in javascript

查看:77
本文介绍了用于在javascript中映射对象的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

< pre class =snippet-code-js lang-js prettyprint-override> 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()))//未捕获的SyntaxError:JSON中的意外标记o位置1



使用<$ c $将地图对象转换为字符串c> toString()现在我无法从字符串转换为map对象。

解决方案

要存储字符串化结果,最好使用普通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.

这篇关于用于在javascript中映射对象的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆