Created
January 27, 2015 22:12
-
-
Save alexserver/971fb8c1682aa5003942 to your computer and use it in GitHub Desktop.
Circular Reference in Javascript, and how to avoid it.
This file contains 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
//https://www.npmjs.com/package/json-stringify-safe | |
var stringify = require("json-stringify-safe"); | |
var a = { | |
type: "Son", | |
name: "John" | |
}; | |
var b = { | |
type: "father", | |
name: "Michael" | |
}; | |
var c = { | |
type: "grandpa", | |
name: "Elias" | |
}; | |
a.father = b; | |
a.grandpa = c; | |
b.son = a; | |
b.father = c; | |
c. grandson = a; | |
c.son = b; | |
try { | |
//Will lead to circular reference while printing in console | |
console.log("Son ", a); | |
//Will lead to error because of the endless conversion | |
console.log("Son JSON Parsed ", JSON.stringify(a)); | |
} | |
catch (ex) { | |
console.log("Error >> ", ex); | |
} | |
finally { | |
//this needs to happen in finally, because of previous conversion. | |
//Will print safe parsed JSON string | |
console.log("Son Safe Parsed ", stringify(a)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment