Skip to content

Instantly share code, notes, and snippets.

@AntoineDrouhin
Created January 22, 2019 12:45
Show Gist options
  • Save AntoineDrouhin/41818c41be10a54d0f73ef38f69b6717 to your computer and use it in GitHub Desktop.
Save AntoineDrouhin/41818c41be10a54d0f73ef38f69b6717 to your computer and use it in GitHub Desktop.
stringify recursive object
/**
* Wrapper for json.stringify that will prevent circular reference error
* and format the output with the provided space
* @param input any
*/
export default function stringify(input: any) {
const seen: Set<any> = new Set<any>()
return JSON.stringify(
input,
(_, value) => {
if (typeof value === 'object' && value !== null) {
if (seen.has(value)) {
return
}
seen.add(value)
}
return value
},
2
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment