Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
95
rated 0 times [  100] [ 5]  / answers: 1 / hits: 38297  / 9 Years ago, sat, march 7, 2015, 12:00:00
var a = new Map([[ 'a', 1 ]]);
a.get('a') // 1

var forStorageSomewhere = JSON.stringify(a);
// Store, in my case, in localStorage.

// Later:
var a = JSON.parse(forStorageSomewhere);
a.get('a') // TypeError: undefined is not a function


Unfortunatly JSON.stringify(a); simply returns '{}', which means a becomes an empty object when restored.



I found es6-mapify that allows up/down-casting between a Map and a plain object, so that might be one solution, but I was hoping I would need to resort to an external dependency simply to persist my map.


More From » json

 Answers
12

Assuming that both your keys and your values are serialisable,



localStorage.myMap = JSON.stringify(Array.from(map.entries()));


should work. For the reverse, use



map = new Map(JSON.parse(localStorage.myMap));

[#67536] Thursday, March 5, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
dayshadelaniej

Total Points: 668
Total Questions: 121
Total Answers: 121

Location: Sao Tome and Principe
Member since Wed, Dec 21, 2022
1 Year ago
dayshadelaniej questions
;