Last active
April 2, 2022 15:58
-
-
Save hamzakaya/24055adf8f5e1e4b65a0316baa1b388f to your computer and use it in GitHub Desktop.
JSON.stringify for circular
This file contains 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
export default function circularStringify(object, { indentation } = {}) { | |
if (Array.isArray(object)) { | |
object = object.map((element) => | |
JSON.parse(JSON.stringify(element, replacer())), | |
) | |
} | |
return JSON.stringify(object, replacer(), indentation) | |
} | |
const replacer = () => { | |
const seen = new WeakSet() | |
return (key, value) => { | |
if (value !== null && typeof value === 'object') { | |
if (seen.has(value)) return '[Circular]' | |
seen.add(value) | |
} | |
return value | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment