Skip to content

Instantly share code, notes, and snippets.

@deepakshrma
Last active April 2, 2020 12:51
Show Gist options
  • Save deepakshrma/7eb0d78aeb4889938a2424f7d681760a to your computer and use it in GitHub Desktop.
Save deepakshrma/7eb0d78aeb4889938a2424f7d681760a to your computer and use it in GitHub Desktop.
const tree = {
name: "A",
children: [
{ name: "A-1", children: [{ name: "A-1-A" }, { name: "A-1-B" }] },
{
name: "B-1",
children: [
{ name: "B-1-A", children: [{ name: "B-11-A" }, { name: "B-11-B" }] },
{ name: "B-1-B" }
]
}
]
};
const searchFn = (tree, name) => {
let result = null;
if (typeof tree !== "object") return result;
if (tree.name === name) return tree;
if (tree.children && tree.children.length) {
tree.children.some(data => (result = searchFn(data, name)));
}
return result;
};
console.log(searchFn(tree, "A-1-A"));
console.log(searchFn(tree, "A-1"));
console.log(searchFn(tree, ""));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment