Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I persist a ES6 Map in localstorage (or elsewhere)?

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.

like image 448
Letharion Avatar asked Mar 07 '15 18:03

Letharion


People also ask

Can we store JavaScript objects directly into localStorage?

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.

What is an ES6 map?

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.

What is map and set in ES6?

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.


1 Answers

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)); 
like image 55
Bergi Avatar answered Oct 07 '22 09:10

Bergi