Created
January 22, 2019 12:45
-
-
Save AntoineDrouhin/41818c41be10a54d0f73ef38f69b6717 to your computer and use it in GitHub Desktop.
stringify recursive object
This file contains hidden or 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
/** | |
* 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