Last active
October 27, 2021 03:29
-
-
Save saitonakamura/d51aa672c929e35cc81fa5a0e31f12a9 to your computer and use it in GitHub Desktop.
Function that replace circular js object dependency with "[Circular]" so it can be consumed by JSON.stringify
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
// DISCLAIMER | |
// Original function was updated to a faster and es5-supporting version by @Quacky2200 | |
var replaceCircular = function(val, cache) { | |
cache = cache || new WeakSet(); | |
if (val && typeof(val) == 'object') { | |
if (cache.has(val)) return '[Circular]'; | |
cache.add(val); | |
var obj = (Array.isArray(val) ? [] : {}); | |
for(var idx in val) { | |
obj[idx] = replaceCircular(val[idx], cache); | |
} | |
cache.delete(val); | |
return obj; | |
} | |
return val; | |
}; | |
// var a = { f: "asd", b: undefined } | |
// var b = { h: 123, a: a } | |
// a.b = b | |
// console.log(JSON.stringify(replaceCircular(a))) | |
// { "f": "asd", "b": { "h": 123, "a": "[Circular]" } } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Wow, you people are great! @Quacky2200 I'll update the original to
replaceCircular6
and mention you if you don't mind