简体   繁体   中英

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

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

You probably don't want to use .map here, because you don't want a mutated array, you just want to find a node. Using a for loop gets the expected result:

 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'); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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