Skip to content

Instantly share code, notes, and snippets.

@shiv19
Last active February 23, 2023 20:19
Show Gist options
  • Save shiv19/b5ffc7190b2894ee8d3e50436972738e to your computer and use it in GitHub Desktop.
Save shiv19/b5ffc7190b2894ee8d3e50436972738e to your computer and use it in GitHub Desktop.
Serialise/Deserialise JavaScript Maps and Sets
function replacer(key, value) {
if (value instanceof Map) {
return { __type: 'Map', value: Object.fromEntries(value) }
}
if (value instanceof Set) {
return { __type: 'Set', value: Array.from(value) }
}
return value
}
function reviver(key, value) {
const resultMap = {
'Set': new Set(value.value),
'Map': new Map(Object.entries(value.value)),
'default': value
};
return resultMap[value?.__type] || resultMap.default;
}
// Serialise
JSON.stringify(obj, replacer)
// Deserialise
JSON.parse(string, reviver)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment