How would one JSON.stringify() a Set?
Things that did not work in Chromium 43:
var s = new Set([\'foo\', \'bar\']);
JSON.stringify(s); // -> \"{}
Use this JSON.stringify replacer:
(because toJSON is a legacy artifact, and a better approach is to use a custom replacer, see https://github.com/DavidBruant/Map-Set.prototype.toJSON/issues/16)
function Set_toJSON(key, value) {
if (typeof value === 'object' && value instanceof Set) {
return [...value];
}
return value;
}
Then:
const fooBar = { foo: new Set([1, 2, 3]), bar: new Set([4, 5, 6]) };
JSON.stringify(fooBar, Set_toJSON)
Result:
"{"foo":[1,2,3],"bar":[4,5,6]}"