将数组装换成tree ,parentId 不确定


interface ArrayTreeOptions {
  list: any[];
  pid?: number|string;
  parentIdKey?: string;
  key?:string;
  level?:number;
  eliminateKey?:any|null;
  eliminateValue?:any|null;
  holdParent?:boolean;
  levelLimit?:any|null
}
/**
 * 构造树型结构数据
 * @param {*} list 数据源
 * @param {*} pid  默认 0
 * @param {*} parentIdKey 父节点字段 默认 'parentId'
 * @param {*} key 节点字段 默认 'id'
 *  @param {*} level 层级
 */
export const arrayToTree=<T>({
  list=[], 
  pid=0,
  parentIdKey="parentId",
  key='id',
  level=0}:ArrayTreeOptions):T[]=>{
  const childrenListMap: any = {};
  const nodeIds: any = {};
  const tree: T[] = [];
  for (const d of list) {
    const parentId = d[parentIdKey];
    if (childrenListMap[parentId] == null) {
      childrenListMap[parentId] = [];
    }
    d['level'] = level;
    nodeIds[d[key]] = d;
    childrenListMap[parentId].push(d);
  }
  for (const d of list) {
    const parentId = d[parentIdKey];
    if (nodeIds[parentId] === undefined) {
      // console.log(nodeIds[parentId],d)
      tree.push(d);
    }else{
      // console.log('nodeIds[parentId]',nodeIds[parentId])
    }
  }
  const adaptToChildrenList = (o: any,level:number=0) => {
    level++
    if (childrenListMap[o[key]] !== null) {
      o['children'] = childrenListMap[o[key]];
    }
    if (o['children']) {
      for (const c of o['children']) {
        c['level'] = level
        adaptToChildrenList(c,level);
      }
    }
  };
  for (const t of tree) {
    adaptToChildrenList(t,level);
  }
  return tree;
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容