The keys of a
Let's stringify
Serialize
Deserialize your
Stringify
Map
can be anything, including objects. But JSON syntax only allows strings as keys... Let's stringify
Map
instance to JSON
...
Serialize Map
instance to JSON
We can't directly stringify the Map instance, therefore we need to convert it to Array first and than stringify.
TypeScript
JSON.stringify(Array.from([...map]))
// or
JSON.stringify(Array.from(map))
// or
JSON.stringify(Array.from(map.entries()))
Output would be exactly the same in all three cases above.
TypeScript
// [["key1", "value"],["key2", "value"]]
Deserialize your JSON
string back to Map
TypeScript
const mapJSON = JSON.stringify([...map])
const deserializedMap = new Map(JSON.parse(mapJSON));
Stringify Map
instance with objects as keys
Let's create the Map with objects as keys:
TypeScript
const map = new Map();
map.set({ label: 'opt1' }, true);
map.set({ label: 'opt2' }, false);
JSON.stringify(Array.from([...map]))
Output should be the following.
TypeScript
// [[{"label":"opt1"},true],[{"label":"opt2"},false]]
Conclusion
In case your keys are strings, you could still use the plain object as a map.
It would be easily stringified and sometimes even faster.
Really very happy to say, your post is very interesting to read. I never stop myself to say something about it. You’re doing a great job. Keep it up.
ReplyDeletemobile phone repair in Auburn Hills
iphone repair in Auburn Hills
cell phone repair in Auburn Hills
tablet repair in Auburn Hills
ipad repair in Auburn Hills
mobile phone repair Auburn Hills
iphone repair Auburn Hills
cell phone repair Auburn Hills
phone repair Auburn Hills
tablet repair Auburn Hills
cheap hidden cameras
ismartalarm camera
dymo label maker
Waterproof Action Camera
Coleman full size air mattress
womens cotton long johns
APPLE WATCH SERIES 3 INFORMATION
Winter Cycling Jackets For Men