Last active
February 23, 2023 20:19
-
-
Save shiv19/b5ffc7190b2894ee8d3e50436972738e to your computer and use it in GitHub Desktop.
Serialise/Deserialise JavaScript Maps and Sets
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
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