Skip to content

Instantly share code, notes, and snippets.

@nachmore
Last active July 13, 2021 07:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nachmore/782723df3dbf8655c70856f10ca67ef6 to your computer and use it in GitHub Desktop.
Save nachmore/782723df3dbf8655c70856f10ca67ef6 to your computer and use it in GitHub Desktop.
Traverse a Javascript object. Particularly useful for dump(this) to grab everything.
dump = (target, match_re, depth, seen) => {
if (depth === undefined) depth = 0
if (seen === undefined) seen = [target]
Object.keys(target).forEach((i, idx) => {
value = target[i] ?? "null";
isObject = (value === Object(value));
// toString() is needed since some items are Symbol which can't be +'d
// to a string
if (!match_re || value.toString().match(match_re)) {
console.log(" ".repeat(depth) + i.toString() + " -> " + value.toString());
}
// avoid recursive objects
if (isObject && value !== target && !seen.includes[value]) {
seen.push(value);
console.log(seen);
dump(value, match_re, depth+1, seen);
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment