Skip to content

Instantly share code, notes, and snippets.

@sphvn
Last active October 26, 2023 21:49
Show Gist options
  • Save sphvn/dcdf9d683458f879f593 to your computer and use it in GitHub Desktop.
Save sphvn/dcdf9d683458f879f593 to your computer and use it in GitHub Desktop.
Recursively traverse object javascript, recurse json js, loop and get key/value pair for JSON
var traverse = function(o, fn) {
for (var i in o) {
fn.apply(this,[i,o[i]]);
if (o[i] !== null && typeof(o[i])=="object") {
traverse(o[i], fn);
}
}
}
// usage
var obj = {'your':'object'};
traverse(obj, function(k,v){
console.log(k + " : " + v);
});
@blaasvaer
Copy link

And when taking nested arrays into account?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment