Last active
July 13, 2021 07:07
-
-
Save nachmore/782723df3dbf8655c70856f10ca67ef6 to your computer and use it in GitHub Desktop.
Traverse a Javascript object. Particularly useful for dump(this) to grab everything.
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
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