简体   繁体   English

使用递归javascript的树搜索

[英]tree search using recursion javascript

I am looking for a way to be able to search in an array, with nested arrays, a node with information. 我正在寻找一种方法,可以在带有嵌套数组的数组中搜索带有信息的节点。 It can be seen as a tree 可以看成是一棵树

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:[...]
              },
              ...
             ]
          },
          ...
         ]
       },
       ...
      ],
    },
    ...
   ]

If I wanted to find the node with name: Bill Gates 如果要查找名称为:Bill Gates的节点

Try this function, but it does not work properly 尝试使用此功能,但无法正常工作

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)
      }
    }
  })
}

In deeper data like Bill Gates Node returns the entire TreeArray, but with all the data that does not contain the name Bill Gates as undefined 在像Bill Gates这样的更深层数据中,Node返回整个TreeArray,但所有不包含名称Bill Gates的数据都为未定义

You probably don't want to use .map here, because you don't want a mutated array, you just want to find a node. 您可能不想在这里使用.map ,因为您不想使用突变数组,而只想找到一个节点。 Using a for loop gets the expected result: 使用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