Last active
November 11, 2015 03:57
-
-
Save chrisl8888/babf57d37cfc2c46a774 to your computer and use it in GitHub Desktop.
Traverse through a tree of json - https://www.quora.com/How-do-you-loop-through-a-complex-JSON-tree-of-objects-and-arrays-in-JavaScript
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
function traverse(x, level) { | |
if (isArray(x)) { | |
traverseArray(x, level); | |
} else if ((typeof x === 'object') && (x !== null)) { | |
traverseObject(x, level); | |
} else { | |
console.log(level + x); | |
} | |
} | |
function isArray(o) { | |
return Object.prototype.toString.call(o) === '[object Array]'; | |
} | |
function traverseArray(arr, level) { | |
console.log(level + "<array>"); | |
arr.forEach(function(x) { | |
traverse(x, level + " "); | |
}); | |
} | |
function traverseObject(obj, level) { | |
console.log(level + "<object>"); | |
for (var key in obj) { | |
if (obj.hasOwnProperty(key)) { | |
console.log(level + " " + key + ":"); | |
traverse(obj[key], level + " "); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment