繁体   English   中英

使用递归javascript的树搜索

[英]tree search using recursion javascript

我正在寻找一种方法,可以在带有嵌套数组的数组中搜索带有信息的节点。 可以看成是一棵树

const data = [
  {
    id: '1-1',
    name: "Factory",
    children: [
      {
        id: '1-1-1',
        name: "Areas",
        children: [
          {                
            id: '1-1-1-1',
            name: "Sales",
            children: [
              {
                id: '1-1-1-1-1',
                name: "Bill Gates",
                children:[...]
              },
              ...
             ]
          },
          ...
         ]
       },
       ...
      ],
    },
    ...
   ]

如果要查找名称为:Bill Gates的节点

尝试使用此功能,但无法正常工作

const getElements = (treeData, text) => {
  return treeData.map(node => {
    const textMatch = node.name.toLowerCase().includes(text.toLowerCase());
    if (textMatch) {
      console.log(node);
      return node;
    } else {
      if (node.children) {
        return getElements(node.children, text)
      }
    }
  })
}

在像Bill Gates这样的更深层数据中,Node返回整个TreeArray,但所有不包含名称Bill Gates的数据都为未定义

您可能不想在这里使用.map ,因为您不想使用突变数组,而只想找到一个节点。 使用for循环可获得预期的结果:

 const data = [{ id: '1-1', name: "Factory", children: [ { id: '1-1-1', name: "Areas", children: [ { id: '1-1-1-1', name: "Sales", children: [ { id: '1-1-1-1-1', name: "Bill Gates", children:[] }, ] }, ] }, ] }]; const getElements = (treeData, text) => { for (let i=0, node = treeData[i]; node; i++) { const textMatch = node.name.toLowerCase().includes(text.toLowerCase()); if (textMatch) { console.log(node); return node; } else if (node.children) { return getElements(node.children, text) } } }; getElements(data, 'Bill Gates'); 

暂无
暂无

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

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