[英]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.