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.
In summary, we can store JavaScript objects in localStorage by first converting them to strings with the JSON. stringify method, then back to objects with the JSON. parse method.
ES6 provides us a new collection type called Map, which holds the key-value pairs in which values of any type can be used as either keys or values. A Map object always remembers the actual insertion order of the keys. Keys and values in a Map object may be primitive or objects. It returns the new or empty Map.
ES6 Sets and Maps Summary An element is a member of the set if the set contains the element. Adding more of the same elements to the set does not increase the number of elements in the set, as only unique values can be added. Maps are a collection of key-value pairs much like regular objects.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With