简体   繁体   English

如何在打字稿中的树内找到树

[英]How to find a tree inside a tree in typescript

let say i have a tree in javascript 假设我在javascript中有一棵树

a1 
--b
----c1
a2
--b2
--b3
----c2

and if i wanted to find c2, it should return a2->b3->c2 如果我想找到c2,它应该返回a2-> b3-> c2

Lets say my json looked like this? 可以说我的json看起来像这样吗?

treeFamily = {
            name : "Parent",
            children: [{
                name : "Child1",
                children: [{
                    name : "Grandchild1",
                    children: []
                },{
                    name : "Grandchild2",
                    children: []
                },{
                    name : "Grandchild3",
                    children: []
                }]
            }, {
                name: "Child2",
                children: []
            }]
        };

You could check if the nested children have the wanted key/value. 您可以检查嵌套的子代是否具有所需的键/值。 Then take the name and hand over the result to the outer call. 然后使用name并将结果移交给外部调用。

 function findPath(array, target) { var path; array.some(({ name, children }) => { var temp; if (name === target) { path = [name]; return true; } if (temp = findPath(children, target)) { path = [name, ...temp]; return true; } }); return path; } var treeFamily = { name: "Parent", children: [{ name: "Child1", children: [{ name: "Grandchild1", children: [] }, { name: "Grandchild2", children: [] }, { name: "Grandchild3", children: [] }] }, { name: "Child2", children: [] }] }; console.log(findPath([treeFamily], 'Grandchild2')); console.log(findPath([treeFamily], 'foo')); 

You can use for...of to search the children by calling the function recursively. 您可以使用for...of通过递归调用函数来搜索子级。 If the target is found, the name is returned, and combined with the previous names. 如果找到目标,则返回名称,并与先前的名称组合。 If not, the function will return undefined . 否则,该函数将返回undefined Alternatively, you can return an empty array. 或者,您可以返回一个空数组。

 const findPath = (targetName, { name, children }) => { if(name === targetName) return [name]; for(const child of children) { const result = findPath(targetName, child); if(result) return [name, ...result]; } // if child not found implicitly return undefined or return [] to get an empty array }; const treeFamily = { name: "Parent", children: [{ name: "Child1", children: [{ name: "Grandchild1", children: [] }, { name: "Grandchild2", children: [] }, { name: "Grandchild3", children: [] }] }, { name: "Child2", children: [] }] }; console.log(findPath('Child2', treeFamily)); console.log(findPath('Grandchild3', treeFamily)); console.log(findPath('Grandchild400', treeFamily)); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM