javascriptjsondictionaryecmascript-6

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

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

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


Solution

  • 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));