使用递归将一维数组转换成tree 结构

2024-03-21  本文已影响0人  冰落寞成

list 转换成tree

  /**
   * 将普通数组转换成tree
   */
    listToTree (list, pid = 0) {
      const tree = []
      list.forEach(item => {
        if (item.pid === pid) {
          const children = this.listToTree(list, item.id)
          if (children.length > 0) {
            item.children = children
          }
          tree.push(item)
        }
      })
      return tree
    },
export const arrayToTree=({list=[], pid=0,parentIdKey="parentId",childrenKey='id'}={})=>{
    const tree = []
    list.forEach(item => {
      console.log('item[parentIdKey]',item[parentIdKey],pid,item[parentIdKey] === pid)
      if (item[parentIdKey] === pid) {
        const children = arrayToTree({list, pid:item[childrenKey],parentIdKey,childrenKey})
        if (children.length > 0) {
          item.children = children
        }
        tree.push(item)
      }
    })
    return tree
}
上一篇下一篇

猜你喜欢

热点阅读