Javascript运行递归数组

时间:2017-10-23 13:48:36

标签: javascript reactjs

我试图在反应应用程序中的数组中递归运行,我这样做了,我想改进我的函数来运行数组:

我的数组:

tree: [
         {
           key: 0 ,
           name: 'menu 1',
           children: [
             {
               key: 1,
               name: 'submenu 1 - 1'
             },{
               key: 2,
               name: 'submenu 1 - 2'
             }
           ]
         },{
           key: 3 ,
           name: 'menu 2',
           children: [
             {
               key: 4,
               name: 'submenu 2 - 1'
             },{
               key: 5,
               name: 'submenu 2 - 2'
             }
           ]
         }
      ]

我以这种方式运行这个数组:

const findInArrayTree = (tree, search) =>{
  let it,
      result

  for (it = 0; it < tree.length; it += 1) {
    result = findNode(tree[it], search);
    if(result !== false){
      return result;
    }
  }
  return result;
};

const findNode = (currentNode, search) => {
    let i,
        currentChild,
        result; 
    if (search == currentNode.key) {
        return currentNode;
    } else {
        // Use a for loop instead of forEach to avoid nested functions
        // Otherwise "return" will not work properly
        if(currentNode.children){
          for (i = 0; i < currentNode.children.length; i += 1) {
            currentChild = currentNode.children[i];
            // Search in the current child
            result = findNode(currentChild, search);
            // Return the result if the node has been found
            if (result !== false) {
                return result;
            }
          }
        }
        // The node has not been found and we have no more options
        return false;
    }
};

有人可以帮助我改善这一点吗?我只想在一个函数中运行,但是我的大脑已被打破了..

1 个答案:

答案 0 :(得分:1)

你可以这样做:

&#13;
&#13;
var tree = [
         {
           key: 0 ,
           name: 'menu 1',
           children: [
             {
               key: 1,
               name: 'submenu 1 - 1'
             },{
               key: 2,
               name: 'submenu 1 - 2'
             }
           ]
         },{
           key: 3 ,
           name: 'menu 2',
           children: [
             {
               key: 4,
               name: 'submenu 2 - 1'
             },{
               key: 5,
               name: 'submenu 2 - 2'
             }
           ]
         }
      ];

function findInTree(items, search) {
    for (var i = 0; i < items.length; i++) {
        var item = items[i];
        if (item.key === search) {
            return item;
        } else if (item.children && item.children.length > 0) {
            var foundInChildren = findInTree(item.children, search);
            if (foundInChildren) {
                return foundInChildren;
            }
        }
    }
}

var found = findInTree(tree, 4);
console.log(found);
&#13;
&#13;
&#13;