繁体   English   中英

Javascript使用递归函数从树中查找节点

[英]Javascript find node from tree with recursive function

我有这样的JavaScript树数据。

 const tree = { children:[ {id: 10, children: [{id: 34, children:[]}, {id: 35, children:[]}, {id: 36, children:[]}]}, {id: 10, children: [ {id: 34, children:[ {id: 345, children:[]} ]}, {id: 35, children:[]}, {id: 36, children:[]} ] }, {id: 11, children: [{id: 30, children:[]}, {id: 33, children:[]}, {id: 3109, children:[]}]} ], id: 45 } const getByID = (tree, id) => { let result = null if (id === tree.id) { return tree } else { if(tree.children){ tree.children.forEach( node=> { result = getByID(node, id) }) } return result } } const find345 = getByID(tree, 345) console.log(find345)

我试图通过它的 id 从这棵树中找到项目。 我正在使用递归函数来迭代树及其子项,但它不会像我预期的那样找到该项目。

它总是返回空值。 预计返回{id: 345, children:[]}

您需要使用允许在查找时短路的方法退出循环。

访问节点但已经找到节点的问题是用后来的错误结果替换结果。 您需要在找到节点的情况下提前退出。

Array#some允许迭代并在返回真实值时退出循环。 在这种情况下,结果是真实的。

 const tree = { children: [{ id: 10, children: [{ id: 34, children: [] }, { id: 35, children: [] }, { id: 36, children: [] }] }, { id: 10, children: [{ id: 34, children: [{ id: 345, children: [] }] }, { id: 35, children: [] }, { id: 36, children: [] }] }, { id: 11, children: [{ id: 30, children: [] }, { id: 33, children: [] }, { id: 3109, children: [] }] }], id: 45 }; const getByID = (tree, id) => { let result = null if (id === tree.id) { return tree } else { if(tree.children){ tree.children.some(node => result = getByID(node, id)); // ^^^^ exit if found // ^^^^^^^^^^^^^^^^^^^^^^^^^^ return & assign } return result; } } const find345 = getByID(tree, 345) console.log(find345)

短一点

 var tree = { children: [{ id: 10, children: [{ id: 34, children: [] }, { id: 35, children: [] }, { id: 36, children: [] }] }, { id: 10, children: [{ id: 34, children: [{ id: 345, children: [] }] }, { id: 35, children: [] }, { id: 36, children: [] }] }, { id: 11, children: [{ id: 30, children: [] }, { id: 33, children: [] }, { id: 3109, children: [] }] }], id: 45 }, getByID = (tree, id) => { var temp; return tree.id === id? tree: (tree.children || []).some(o => temp = getByID(o, id)) && temp; }; console.log(getByID(tree, 345));

我们也可以对递归函数使用reduce方法

function findAllByKey(obj, keyToFind) {
  return Object.entries(obj)
    .reduce((acc, [key, value]) => (key === keyToFind)
      ? acc.concat(value)
      : (typeof value === 'object' && value)
      ? acc.concat(findAllByKey(value, keyToFind))
      : acc
    , []) || [];
}

暂无
暂无

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

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