Skip to content

Instantly share code, notes, and snippets.

@ianldgs
Last active January 3, 2023 15:25
Show Gist options
  • Save ianldgs/a447458619e24b196d75 to your computer and use it in GitHub Desktop.
Save ianldgs/a447458619e24b196d75 to your computer and use it in GitHub Desktop.
Check if JSON has circular reference
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