Forked from Trindaz/Circular reference JSON.stringify wrapper
Created
January 24, 2014 17:49
-
-
Save jiverson/8602377 to your computer and use it in GitHub Desktop.
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
| var repeatingArray = [4, 5, 6]; | |
| var circularObj = { | |
| a: 1, | |
| b: 1, | |
| c: "an allowed repeating string", | |
| d: "an allowed repeating string", | |
| e: repeatingArray, | |
| f: repeatingArray, | |
| g: [ | |
| repeatingArray, | |
| repeatingArray | |
| ] | |
| }; | |
| circularObj.h = circularObj; | |
| var myObj = { | |
| co: circularObj | |
| }; | |
| function stringifyOnce(obj, replacer, indent){ | |
| var printedObjects = []; | |
| var printedObjectKeys = []; | |
| function printOnceReplacer(key, value){ | |
| var printedObjIndex = false; | |
| printedObjects.forEach(function(obj, index){ | |
| if(obj===value){ | |
| printedObjIndex = index; | |
| } | |
| }); | |
| if(printedObjIndex && typeof(value)=="object"){ | |
| return "(see " + value.constructor.name.toLowerCase() + " with key " + printedObjectKeys[printedObjIndex] + ")"; | |
| }else{ | |
| var qualifiedKey = key || "(empty key)"; | |
| printedObjects.push(value); | |
| printedObjectKeys.push(qualifiedKey); | |
| if(replacer){ | |
| return replacer(key, value); | |
| }else{ | |
| return value; | |
| } | |
| } | |
| } | |
| return JSON.stringify(obj, printOnceReplacer, indent); | |
| } | |
| console.log(stringifyOnce(myObj, undefined, 4)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment