JS函数 在树中寻找节点 / 在数组中查找下级对象 TypeScript+迭代方式

介绍一个函数,实现在树中寻找节点,或者叫在数组中查找下级对象。采用迭代方法,支持Typescript,提供单元测试样例。

由于我需要这么一个功能,后来搜索了Stackoverflow,根据一个网友的代码,增强了一下功能。除了复杂度有点高,其它感觉还可以,分享出来,节省大家时间。

Stackoverflow回答的地址:https://stackoverflow.com/a/67432192/8819175,核心来自Erick Petrucelli的代码。

function searchTree(
  tree: Record<string, any>[],
  value: unknown,
  key = 'value',
  withChildren = false,
) {
  let result = null;
  if (!Array.isArray(tree)) return result;

  for (let index = 0; index < tree.length; index += 1) {
    const stack = [tree[index]];
    while (stack.length) {
      const node = stack.shift()!;
      if (node[key] === value) {
        result = node;
        break;
      }
      if (node.children) {
        stack.push(...node.children);
      }
    }
    if (result) break;
  }
  if (withChildren !== true) {
    delete result?.children;
  }

  return result;
}

单元测试样例在:https://gist.github.com/aspirantzhang/a369aba7f84f26d57818ddef7d108682

点赞