Created
February 22, 2019 21:55
-
-
Save dschnare/e83ab896d9970d9436678d2a684529bd to your computer and use it in GitHub Desktop.
Object graph walker
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
// Walk an object graph, calling the visit function with | |
// value, key, and object at each level. | |
function walk (o, visit) { | |
visit(o, '', o) | |
if (o && (Array.isArray(o) || Object(o) === o)) { | |
let stack = [ o ] | |
while (stack.length) { | |
let obj = stack.shift() | |
for (let k in obj) { | |
const v = obj[k] | |
if (v && (Array.isArray(v) || Object(v) === v)) { | |
stack.push(v) | |
} | |
visit(v, k, obj) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment