Created
August 2, 2023 19:35
-
-
Save dfkaye/5568b81280e27a36875065ca71d03e9d to your computer and use it in GitHub Desktop.
polyfill to support serializing a JS Set
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
// 2 August 2023 | |
// set.toJSON | |
// when you absolutely must serialize a set | |
// using JSON.stringify() which normally | |
// returns set: {} | |
Set.prototype.toJSON = function toJSON() { | |
var set = {}; | |
for (var [k, v] of this.entries()) { | |
set[k] = v; | |
} | |
return set; | |
} | |
/* test it out */ | |
var o = { set: new Set(['1', 'X']) }; | |
o.set.add("K"); | |
o.set.add(0); | |
console.log(o); | |
// { set: Set(4) [ "1", "X", "K", "0" } | |
JSON.stringify(o, null, 2); | |
/* | |
'{ | |
"set": { | |
"0": 0, | |
"1": "1", | |
"X": "X", | |
"K": "K" | |
} | |
}' | |
*/ | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment