Created
September 20, 2021 13:11
-
-
Save rakia/85ab02f74c876b521cc0e2c1fd72143a to your computer and use it in GitHub Desktop.
Circular Reference in JavaScript
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 circularReference = {otherData: 123}; | |
circularReference.myself = circularReference; | |
JSON.stringify(circularReference); // returns --> TypeError: cyclic object value | |
const getCircularReplacer = () => { | |
const seen = new WeakSet(); | |
return (key, value) => { | |
if (typeof value === "object" && value !== null) { | |
if (seen.has(value)) { | |
return; | |
} | |
seen.add(value); | |
} | |
return value; | |
}; | |
}; | |
JSON.stringify(circularReference, getCircularReplacer()); // returns --> {"otherData":123} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment