Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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);
});
@orlaqp

This comment has been minimized.

Copy link

orlaqp commented Jul 16, 2018

Simple Awesome!!! Thanks!

Here is a small modification (Typescript) in case someone finds it useful also

export function traverse(o: any, fn: (obj: any, prop: string, value: any) => void) {
    for (const i in o) {
        fn.apply(this, [o, i, o[i]]);
        if (o[i] !== null && typeof(o[i]) === 'object') {
            traverse(o[i], fn);
        }
    }
}
@moslemsaid

This comment has been minimized.

Copy link

moslemsaid commented Oct 1, 2019

ممنون

thanks ;-)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.