Created
September 14, 2021 00:05
-
-
Save bsidhom/adf6f5251f95a9cefd7dbf3ea02d36df to your computer and use it in GitHub Desktop.
JSON serialize the window object by removing cycles
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
// Taken from https://stackoverflow.com/a/9382383 | |
let decycle; | |
decycle = (obj, stack = []) => { | |
if (!obj || typeof obj !== 'object') { | |
return obj; | |
} | |
if (stack.includes(obj)) { | |
return null; | |
} | |
let s = stack.concat([obj]); | |
return Array.isArray(obj) ? obj.map(x => decycle(x, s)) : | |
Object.fromEntries(Object.entries(obj).map( | |
([k, v]) => [k, decycle(v, s)])); | |
}; | |
console.log(JSON.stringify(decycle(window))); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment