Skip to content

Instantly share code, notes, and snippets.

@kendru
Last active October 31, 2017 22:42
Show Gist options
  • Save kendru/ba4c0596cc7f1d42c34868b199310678 to your computer and use it in GitHub Desktop.
Save kendru/ba4c0596cc7f1d42c34868b199310678 to your computer and use it in GitHub Desktop.
Find a node matching a predicate in a generic JS tree
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