Created
October 13, 2018 09:48
-
-
Save adil1214/4e00857d8eb9b91a13f6f47edd108152 to your computer and use it in GitHub Desktop.
a JSON.stringify alternative to convert circular object structures to json.
This file contains 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
// converting circular structure to json | |
// source: https://stackoverflow.com/a/48254637/8717257 | |
const customStringify = function (v) { | |
const cache = new Set(); | |
return JSON.stringify(v, function (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; | |
}, 2); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment