簡體   English   中英

如何在打字稿中的樹內找到樹

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

假設我在javascript中有一棵樹

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

如果我想找到c2,它應該返回a2-> b3-> c2

可以說我的json看起來像這樣嗎?

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

您可以檢查嵌套的子代是否具有所需的鍵/值。 然后使用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')); 

您可以使用for...of通過遞歸調用函數來搜索子級。 如果找到目標,則返回名稱,並與先前的名稱組合。 否則,該函數將返回undefined 或者,您可以返回一個空數組。

 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