树搜索使用递归javascript

问题描述 投票:0回答:1

我正在寻找一种能够在数组中搜索的方法,包括嵌套数组,包含信息的节点。它可以看作是一棵树

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) => {
  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的数据都是undefined

javascript reactjs
1个回答
0
投票

你可能不想在这里使用.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');
© www.soinside.com 2019 - 2024. All rights reserved.