Last active
January 3, 2023 15:25
-
-
Save ianldgs/a447458619e24b196d75 to your computer and use it in GitHub Desktop.
Check if JSON has circular reference
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
function isCyclic (obj) { | |
var seenObjects = []; | |
function detect (obj) { | |
if (obj && typeof obj === 'object') { | |
if (seenObjects.indexOf(obj) !== -1) { | |
return true; | |
} | |
seenObjects.push(obj); | |
for (var key in obj) { | |
if (obj.hasOwnProperty(key) && detect(obj[key])) { | |
console.log(obj, 'cycle at ' + key); | |
return true; | |
} | |
} | |
} | |
return false; | |
} | |
return detect(obj); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment