Y_Shmily

导航

一维JSON转树结构

const treeFormat = (arr: any) => {
  let map: any = {}; // 构建map
  // 构建以id为键 当前数据为值
  arr.forEach((item: any) => {
    item["children"] = [];
    map[item['id']] = item;
  });
  const res: any = {
    data:[],
    other:[]
  };
  arr.forEach((child: any) => {
    const mapItem = map[child['parentId']]; // 判断当前数据的id是否存在map中;
    if (mapItem) {
      // 存在则表示当前数据不是最顶层数据
      (mapItem["children"] || (mapItem["children"] = [])).push(child);
    } else {
      // 不存在则是组顶层数据
      child['parentId'] === 0 ? res.data.push(child):res.other.push(child)      
    }
  });
  map = null;
  return res;
}

 

posted on 2022-09-02 17:18  Y_Shmily  阅读(94)  评论(0编辑  收藏  举报