树结构查找

前言

每次遇到都是新写,很烦人,决定记录下来,下次直接copy

代码

const findItemFromTree = (data, key, val) => {
  let res;
  // 处理器
  const handel = (dataChildren) => {
    for (let index = 0; index < dataChildren.length; index++) {
      const element = dataChildren[index];
      if (element[key] === val) {
        res = element;
        break;
      } else {
        if (element.children) {
          handel(element.children);
        }
      }
    }
    return res;
  };

  // 处理成标准的 有根节点的数结构(就是洁癖 树结构难道不应该有根节点吗?)
  if (data instanceof Array) {
    const newData = {
      id: 0,
      children: data,
    };
    return handel(newData.children);
  } else {
    return handel(data);
  }
};

// 查找树结构中 name为张三的人
const res = findItemFromTree(treeData, "name", "张三");
console.log(res);
posted @ 2023-03-15 18:07  丁少华  阅读(26)  评论(0编辑  收藏  举报