Created
August 2, 2023 19:29
-
-
Save dfkaye/4515b9667b04ea7ca0d4b1061acff0c0 to your computer and use it in GitHub Desktop.
polyfill to support JSON.stringify over JS Maps
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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