如何将正常数据转为树结构

发布时间 2023-10-23 14:40:13作者: 芮艺
listToTree(list) {
   const result = [] // 用于存放结果
   const map = {} // 用于存放 list 下的节点

   // 1. 遍历 list,将 list 下的所有节点以 id 作为索引存入 map
   for (const item of list) {
     map[item.id] = { ...item } // 浅拷贝
   }

   // 2. 再次遍历,将根节点放入最外层,子节点放入父节点
   for (const item of list) {
     // 3. 获取节点的 id 和 父 id
     const { id, parentId } = item // ES6 解构赋值
     // 4. 如果是根节点,存入 result
     if (item.parentId == 0) {
       result.push(map[id])
     } else {
       // 5. 反之,存入到父节点
       map[parentId].children
         ? map[parentId].children.push(map[id])
         : (map[parentId].children = [map[id]])
     }
   }
   return result
 },

const tree = this.listToTree(response.data)
console.log('====tree====', tree)