两个比较好用的JS方法,用来处理树形结构!

一、平级结构转树形结构

/**
 * 平级结构转树形结构
 *
 * 示例:const jsonDataTree = listTransToTreeData(jsonData, 'id', 'pid', 'chindren');
 * @param list 平级数据列表
 * @param idStr id的字符串
 * @param pidStr 父id字符串
 * @param chindrenStr children的字符串
 */
export const listTransToTreeData = (list: any, idStr: string, pidStr: string, chindrenStr: string) => {
  let r = [], hash: any = {}, id = idStr, pid = pidStr, children = chindrenStr, i = 0, j = 0, len = list.length;
  for (; i < len; i++) {
    hash[list[i][id]] = list[i];
  }
  for (; j < len; j++) {
    let aVal = list[j], hashVP = hash[aVal[pid]];
    if (hashVP) {
      !hashVP[children] && (hashVP[children] = []);
      hashVP[children].push(aVal);
    } else {
      r.push(aVal);
    }
  }
  return r;
}

二、遍历树形结构并做一些处理事情


/**
 * 遍历处理树形结构
 * @param list 树形结构列表
 * @param childName 子节点属性名,一般是children
 * @param func 每个节点要执行的方法
 * @param isOnlyLeaf 是否只在叶子节点执行该方法
 * @param isChildCallBackFn 判断是否有children属性时执行的方法
 */
export function ergodicNodes(list: { [x: string]: any; }[],
                             childName: string | number,
                             func: (arg0: { [x: string]: any; }) => void, isOnlyLeaf: any,
                             isChildCallBackFn: Function) {
  list.forEach((item: { [x: string]: any; }) => {
    if (item[childName] && item[childName].length > 0) {
      isChildCallBackFn(item);
      ergodicNodes(item[childName], childName, func, isOnlyLeaf, isChildCallBackFn);
      if (!isOnlyLeaf) {
        for (let key in item) {
          func(item)
        }
        return
      }
    } else {
      for (let key in item) {
        func(item)
      }
      return
    }
  })
  return list;
}

ergodicNodes的用法示例

const treeList: any[] = listTransToTreeData(JSON.parse(JSON.stringify(_treeData.data)), 'id', 'pid', 'children');
// 每个节点执行的方法
const callback_fn = (item: any) => {
  item.key = item.id;
  item.title = item.name;
  if(item.schemaName && item.pid === null) item.icon = <UserOutlined />;
  if(item.schemaName && item.tableName) item.icon = <TableOutlined />;
};
// 有children属性时执行的方法
const child_callback = (item: any) => {};
const convertTree = ergodicNodes(treeList, 'children', callback_fn, false, child_callback);
setTreeData(convertTree);
posted @   SuanYunyan  阅读(444)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· Manus爆火,是硬核还是营销?
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
点击右上角即可分享
微信分享提示