在写组织相关的业务中,会经常写一些递归来实现业务,本文记录下项目中用到的递归

后端给到的组织树的结构如下

[
  {
    id:1,
    name:'组织1',
    children:[
      {
        id:2,
        name:'组织1-1',
      },
      {
        id:3,
        name:'组织1-2',
      }
    ]
  }
]
/**
 * 找上级id集合
 * tem是递归使用
 */
findUpId(data, targetId, tem) {
  if (tem === undefined) {
    tem = []
  }
  for (let i = 0; i < data.length; i++) {
    const tmpArr = tem.concat()
    tmpArr.push(data[i].id)
    if (targetId === data[i].id) {
      return tmpArr
    }
    if (data[i].children) {
      const findResult = this.findUpId(data[i].children, targetId, tmpArr)
      if (findResult) {
        return findResult
      }
    }
  }
}
// 寻找下级
findChildren(data, id) {
  for (let i = 0; i < data.length; i++) {
    const item = data[i]
    if (item.id === id) {
      return item.children
    } else {
      if (item.children) {
        const val = this.findChildren(item.children, id)
        // 注意:这里判断,有值就return,没有值就会继续走循环
        if (val) {
          return val
        }
      }
    }
  }
}
// 判断是否有下级
hasChildren(data, id) {
  let res = ''
  for (let i = 0; i < data.length; i++) {
    if (data[i].id === id) {
      res = !!data[i].children
      break
    } else {
      if (data[i].children) {
        return this.hasChildren(data[i].children, id)
      }
    }
  }
  return res
}
// 寻找符合要求的id,禁用自身以及下级
cascaderDisable(data, id) {
  for (let i = 0; i < data.length; i++) {
    if (data[i].id === id) {
      data[i].children && this.DisableSub(data[i].children)
      data[i].disabled = true
      break
    } else {
      // 递归children
      if (data[i].children) {
        this.cascaderDisable(data[i].children, id)
      }
    }
  }
}
// 二维数组转树形结构
// 通过pid找关系
function arrayToTree(items) {
  const result = []; // 存放结果集
  const itemMap = {}; //
  for (const item of items) {
    const { id } = item;
    const { pid } = item;

    if (!itemMap[id]) {
      itemMap[id] = {
        children: [],
      };
    }

    itemMap[id] = {
      ...item,
      children: itemMap[id].children,
    };

    const treeItem = itemMap[id];

    if (pid === 0) {
      result.push(treeItem);
    } else {
      if (!itemMap[pid]) {
        itemMap[pid] = {
          children: [],
        };
      }
      itemMap[pid].children.push(treeItem);
    }
  }
  return result;
}