递归遍历树结构

export function getFirstNode(data, field, params) {
  let node = null;
  return function getNodebyParams(data, field, params) {
    //1.第一层 root 深度遍历整个data
    for (var i = 0; i < data.length; i++) {
      if (node) {
        break;
      }
      var obj = data[i];
      if (obj[field] === params) {
        //找到了与params匹配的节点,结束递归
        node = obj;
        break;
      } else {
        if (obj.children && obj.children.length) {
          //递归往下找
          getNodebyParams(obj.children, field, params);
        } else {
          //跳出当前递归,返回上层递归
          continue;
        }
      }
    }
    //6.返回结果obj
    return {
      node: node
    };
  };
}

调用:

import { getFirstNode } from 'common/js/utils/utils';
let node = getFirstNode()(result[0].children, 'location', 'MENU1');
console.log(node)

你可能感兴趣的:(递归遍历树结构)