Last active
July 9, 2019 11:04
-
-
Save lukas-zech-software/fab77f7eb216d38f027ad8fd5347b1cb to your computer and use it in GitHub Desktop.
Detect circular references in objects
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
// http://blog.vjeux.com/2011/javascript/cyclic-object-detection.html. | |
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