Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
How do Map keys get restored after it's been serialized.
Map.prototype.toJSON = function() {
// somehow iterate keys and values into an array pair?
// for now, I'll fake it.
return '[ [ { "foo": "whatever" }, [ 1, 2, 3, 4, 5 ] ], [ {}, "my key is a plain object" ] ]';
};
function Key(foo) {
this.foo = foo;
}
var map = new Map(),
key = new Key("whatever"),
obj = {};
map.set(key, [ 1, 2, 3, 4, 5 ]);
map.set(obj, "my key is a plain object");
console.log( map.get(key) ); // [ 1, 2, 3, 4, 5 ]
console.log( map.get(obj) ); // "my key is a plain object"
console.log( map.toJSON() );
// [ [ { "foo": "whatever" }, [ 1, 2, 3, 4, 5 ] ], [ {}, "my key is a plain object" ] ]
Now imagine this map is stored in some kind of NoSQL
document store and will be later pulled out by some
other functionality in our application.
How are the map keys (references) revived _into_scope_?
console.log( JSON.parse(map.toJSON()) );
Obviously we can revive the Map:
new Map(JSON.parse(map.toJSON()));
But how do "key" and "obj" get restored?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment