Skip to content

Instantly share code, notes, and snippets.

@dfkaye
Created August 2, 2023 19:35
Show Gist options
  • Save dfkaye/5568b81280e27a36875065ca71d03e9d to your computer and use it in GitHub Desktop.
Save dfkaye/5568b81280e27a36875065ca71d03e9d to your computer and use it in GitHub Desktop.
polyfill to support serializing a JS Set
// 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