使用jQuery / JS序列化Map对象 [英] Serialize Map object with jQuery/JS
问题描述
[这是关于SO的第一个问题,所以对我的任何错误道歉]
[This is first question on SO, so apologize me for any mistake]
我正在尝试在Cookie中保存地图,如下所示。
I'm trying to save a Map, like the one below, in a cookie.
var myMap = new Map();
myMap.set("k1", {
a1: "...",
a2: "...",
a3: "..."
});
为此,我必须格式化为JSON。我尝试了很多方法,例如:
For this, I have to format as JSON. I tried many methods, like:
$.toJSON(myMap)
$.param(myMap)
JSON.stringify(myMap)
但它们似乎都不起作用......
But none of them seems to work...
所以,我这样做了:
var serial = [];
myMap.forEach(function(value){
serial.push(value);
});
var result = $.toJSON(serial)
(必须在解码时重建密钥JSON ...)
(Having to reconstruct the key on decoding the JSON...)
有一种更好的方法来序列化一个Map对象吗?
There is a better way to serialize a Map object?
推荐答案
不完全是典型的stringify,但您可以使用扩展运算符与 JSON.stringify()
结合使用,它将为您提供一个数组。 ..
Not exactly a typical "stringify", but you can use the spread operator combined with JSON.stringify()
, that will give you an array...
var myMap = new Map();
myMap.set("k1", { a1: "...", a2: "...", a3: "..." });
myMap.set("k2", { b1: "...", b2: "...", b3: "..." });
var myJSON = JSON.stringify([...myMap]);
alert(myJSON);
这会给你......
This will give you...
[["k1",{"a1":"...","a2":"...","a3":"..."}],["k2",{"b1":"...","b2":"...","b3":"..."}]]
并再次将其转换为地图...
And to convert it to Map again...
var recoveredMap = new Map(JSON.parse(myJSON));
这篇关于使用jQuery / JS序列化Map对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!