How to serialize a Map in javascript?

I guess the whole point of Maps/Dictionaries is that you can use objects as keys in them, so:

let a = {}, b = {}, m = new Map();

m.set(a,b);
m.get(a); // b

So you get b since you have a reference on a. Let's say you serialize the Map by creating an Array of arrays, and stringify that to json:

function serialize (map) {
  return JSON.stringify([...map.entries()])
}

let s = serialize(m); // '[[{}, {}]]'
                      // '[[<key>, <val>], … ]'

Than you could:

let m2 = JSON.parse(s).reduce((m, [key, val])=> m.set(key, val) , new Map());

But the question now is: How to get a certain key? Since there does not exist any reference, due to the fact that all objects have been stringified and recreated, it is not possible to query a dedicated key.

So all that would only work for String keys, but that really takes most of power of maps, or in other words, reduces them to simple objects, what is the reason maps were implemented.


-- edit: Added the missing JSON Stringify function during serialization -

There is a native way of doing this in Javascript.

the Map object has a method called entries() that returns an iterator that will yield each entry in the map as an array with 2 values in it. It will look like [key, value].

To avoid writing any looping code yourself, you can use Array.from() which can consume an iterator and extract each item from it. Having that, the following will give you your Map object in a serialized form.

let mySerialMap = JSON.stringify(Array.from(myMap.entries()))
console.log(mySerialMap)

Now, that's not even the coolest part. But before getting there, let me show you one possible way of using the Map constructor.

let original = new Map([
  ['key1', 'the-one-value']
  ['second-key, 'value-two']
])

The array of array that you can see being passed to the Map object is in the same format as what you get from using Array.from(myMap.entries()).

So you can rebuild you map in a single line using the following sample code:

let myMap = new Map(JSON.parse(mySerialMap))

And you can use myMap as you would any Map.

let myMap = new Map(JSON.parse(mySerialMap))
let first = myMap.get('some-key')
myMap.set('another-key', 'some value')

Tags:

Javascript