Skip to content

Instantly share code, notes, and snippets.

@rakia
Created September 20, 2021 13:11
Show Gist options
  • Save rakia/85ab02f74c876b521cc0e2c1fd72143a to your computer and use it in GitHub Desktop.
Save rakia/85ab02f74c876b521cc0e2c1fd72143a to your computer and use it in GitHub Desktop.
Circular Reference in JavaScript
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