Created
November 20, 2018 11:57
-
-
Save boton/477d7bb080f8f5643d68035b65e9c4b7 to your computer and use it in GitHub Desktop.
Safe stringify (avoid circular reference)
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
| // borrowed from https://stackoverflow.com/questions/11616630/json-stringify-avoid-typeerror-converting-circular-structure-to-json/48254637#48254637 | |
| const safeStringify = v => { | |
| const cache = new Set(); | |
| return JSON.stringify(v, (key, value) => { | |
| if (typeof value === 'object' && value !== null) { | |
| if (cache.has(value)) { | |
| // Circular reference found, discard key | |
| return; | |
| } | |
| // Store value in our set | |
| cache.add(value); | |
| } | |
| return value; | |
| }); | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment