Last active
August 29, 2015 14:12
-
-
Save morficus/7d7e9a0dcb854f7297d1 to your computer and use it in GitHub Desktop.
Custom replacer for JSON.stringify, specifically for handling circular references
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
| //src: http://stackoverflow.com/a/11616993/1021300 | |
| //replace this empty object with a references to the circular one | |
| var objectToPrint = {}; | |
| var cache = [], | |
| output; | |
| output = JSON.stringify(objectToPrint, function(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; | |
| }, 2); | |
| cache = null; // Enable garbage collection | |
| console.log(output); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment