Skip to content

Instantly share code, notes, and snippets.

@bsidhom
Created September 14, 2021 00:05
Show Gist options
  • Save bsidhom/adf6f5251f95a9cefd7dbf3ea02d36df to your computer and use it in GitHub Desktop.
Save bsidhom/adf6f5251f95a9cefd7dbf3ea02d36df to your computer and use it in GitHub Desktop.
JSON serialize the window object by removing cycles
// 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