JS 将列表转成树形结构数据

一、背景

联调发现有些后端返回List 但是前后需要转树形结构

二、实现

点击查看代码
import _, { isArray } from 'lodash'



/**
 * 将列表转成树形结构数据
 * @param nodes 列表数据
 * @param options 可选参数,{idKey, pIdKey, childrenKey}
 * @returns {[]} 树形结构数据
 */
export function transformToTree(nodes, options = null) {

  // 默认值 id parentId children 来组装 树形,可以通过 传进来的参数进行更改
  options = Object.assign({ idKey: 'id', parentKey: 'parentId', childrenKey: 'children' }, options)
  const { idKey, parentKey, childrenKey } = options
  if (!idKey || idKey === '' || !nodes) return []
  if (isArray(nodes)) {
    const r = []
    const tmpMap = []
    for (let i = 0, l = nodes.length; i < l; i++) {
      tmpMap[nodes[i][idKey]] = nodes[i]
    }
    for (let i = 0, l = nodes.length; i < l; i++) {
      if (tmpMap[nodes[i][parentKey]] && nodes[i][idKey] !== nodes[i][parentKey]) {
        if (!tmpMap[nodes[i][parentKey]][childrenKey]) { tmpMap[nodes[i][parentKey]][childrenKey] = [] }
        tmpMap[nodes[i][parentKey]][childrenKey].push(nodes[i])
      } else {
        r.push(nodes[i])
      }
    }
    return r
  } else {
    return [nodes]
  }
}

调用transformToTree()

点击查看代码
// 默认值 id parentId children 来组装 树形,可以通过 传进来的参数进行更改

// 正常调用
listGeognameCategories().then(data => {
      const list = data.content
      this.geognameCategories = transformToTree(list)
      console.log(this.geognameCategories)
    })

结果:

image

调用transformToTree()自定义父节点树形名称

点击查看代码
// 修改父节点 属性名
listSmalls().then(data => {
      this.depts = transformToTree(data, { parentKey: 'pid' })
      console.log(this.depts)
    })

image

tree.js 树形工具类

三、遇到的报错

四、参考博客

posted @ 2023-09-20 16:45  林财钦  阅读(732)  评论(0)    收藏  举报