Skip to content

Instantly share code, notes, and snippets.

@saitonakamura
Last active October 27, 2021 03:29
Show Gist options
  • Save saitonakamura/d51aa672c929e35cc81fa5a0e31f12a9 to your computer and use it in GitHub Desktop.
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
// 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]" } }
@saitonakamura
Copy link
Author

Wow, you people are great! @Quacky2200 I'll update the original to replaceCircular6 and mention you if you don't mind

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment