Skip to content

Instantly share code, notes, and snippets.

@sphvn

sphvn/traverse.js

Last active Sep 30, 2020
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 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 moslemsaid commented Oct 1, 2019

ممنون

thanks ;-)

@rmkane

This comment has been minimized.

Copy link

@rmkane rmkane commented Mar 23, 2020

I modified this to track scope.

const traverse = function(o, fn, scope = []) {
  for (let i in o) {
    fn.apply(this, [i, o[i], scope]);
    if (o[i] !== null && typeof o[i] === "object") {
      traverse(o[i], fn, scope.concat(i));
    }
  }
}

traverse(myObject, (key, value, scope) => {
  if (value === 'Some Value') {
    console.log(`Position: myObject[${scope.concat(key).map(k => isNaN(k) ? `'${k}'` : k).join('][')}]`);
  }
});
@Tyler-V

This comment has been minimized.

Copy link

@Tyler-V Tyler-V commented Sep 22, 2020

These are great, 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.