Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save jochemstoel/9f279f493b1a538f7e9cdd9e31f34fa9 to your computer and use it in GitHub Desktop.
Save jochemstoel/9f279f493b1a538f7e9cdd9e31f34fa9 to your computer and use it in GitHub Desktop.
Circular JSON Stringify
function circularJSONStringify(obj) {
const cache = [];
const result = JSON.stringify(obj, (key, value) => {
if (typeof value === 'object' && value !== null) {
if (cache.indexOf(value) !== -1) {
// Circular reference found, discard key
return;
}
// Store value in our collection
cache.push(value);
}
return value;
});
cache.length = 0;
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment