扁平数据转tree与tree数据扁平化

首先当我们拿到扁平化数据时候但展示出tree形状 需要我们改变数据

下面是将举两个数据改造的例子:

  一是扁平化,具有层级递进关系的 tree 数据,转换为扁平结构的的 flat 数据

  二是反扁平化,扁平结构的 flat 数据,转换为具有层级递进关系的  tree 数据

一 :扁平化函数

方法一
function
treeToFlat (treeList, flatList) { treeList.map(e => { flatList.push(e) // 递归:有条件的自己调用自己,条件是 e.children.length 为真 if (e.children && e.children.length) { treeToFlat(e.children, flatList) } }) // console.log('扁平化后:', flatList) return flatList }

 

方法2
for (var i = 0; i < arr.length; i++) { if (arr[i].children && arr[i].children.length > 0) { this.OneD(arr[i].children); } else { this.allrouter.push(arr[i]); } }

 

 

 

二:反扁平化函数

function flatToTree (flatList, treeList) {
    flatList.map(e => {
      // 以 e.pid===null,作为判断是不是根节点的依据,或者直接写死根节点(如果确定的话),
      // 具体以什么作为判断根节点的依据,得看数据的设计规则,通常是判断层级或是否代表根节点的标记
      if (e.pid === null) {
        // 避免出现重复数据
        const index = treeList.findIndex(sub => sub.id === e.id)
        if (index === -1) {
          treeList.push(e)
        }
      }
 
      flatList.map(e2 => {
        if (e2.pid === e.id) {
          // 避免出现重复数据
          const index = e.children.findIndex(sub => sub.id === e2.id)
          if (index === -1) {
            e.children.push(e2)
          }
        }
      })
    }) 
}

 

   

  

posted @ 2022-07-21 17:04  Qing`ing  阅读(270)  评论(0编辑  收藏  举报