Skip to content

Instantly share code, notes, and snippets.

@dfkaye
Created August 2, 2023 19:29
Show Gist options
  • Save dfkaye/4515b9667b04ea7ca0d4b1061acff0c0 to your computer and use it in GitHub Desktop.
Save dfkaye/4515b9667b04ea7ca0d4b1061acff0c0 to your computer and use it in GitHub Desktop.
polyfill to support JSON.stringify over JS Maps
// 1 August 2023
// map.toJSON
// when you absolutely must serialize a map
// using JSON.stringify() which normally
// returns map: {}
Map.prototype.toJSON = function toJSON() {
var map = {};
for (var [k, v] of this.entries()) {
map[k] = v;
}
return map;
}
/* test it out */
var o = { map: new Map };
o.map.set("KEY", 'VALUE');
o.map.set(12312312, 'asdfadfadsf');
console.log(o);
// { map: Map { KEY → "VALUE", 12312312 → "asdfadfadsf" } }
JSON.stringify(o, null, 2);
/*
'{
"map": {
"12312312": "asdfadfadsf",
"KEY": "VALUE"
}
}'
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment