Last active
October 31, 2017 22:42
-
-
Save kendru/ba4c0596cc7f1d42c34868b199310678 to your computer and use it in GitHub Desktop.
Find a node matching a predicate in a generic JS tree
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
function findNode(node, pred) { | |
if (pred(node)) { | |
return node; | |
} | |
if (typeof node == 'object' && node.constructor == Object) { | |
for (var prop in node) { | |
if (node.hasOwnProperty(prop)) { | |
let foundNode = findNode(node[prop], pred); | |
if (foundNode) { | |
return foundNode; | |
} | |
} | |
} | |
} else if (Array.isArray(node)) { | |
for (let elem of node) { | |
let foundNode = findNode(elem, pred); | |
if (foundNode) { | |
return foundNode; | |
} | |
} | |
} | |
return false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment