Skip to content

Instantly share code, notes, and snippets.

@DevYam
Created June 29, 2020 06:32
Show Gist options
  • Save DevYam/1cc4b2eb47b54787f401cf6d615d241d to your computer and use it in GitHub Desktop.
Save DevYam/1cc4b2eb47b54787f401cf6d615d241d to your computer and use it in GitHub Desktop.
// safely handles circular references
JSON.safeStringify = (obj, indent = 2) => {
let cache = [];
const retVal = JSON.stringify(
obj,
(key, value) =>
typeof value === "object" && value !== null
? cache.includes(value)
? undefined // Duplicate reference found, discard key
: cache.push(value) && value // Store value in our collection
: value,
indent
);
cache = null;
return retVal;
};
// Example:
console.log('options', JSON.safeStringify(options))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment