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)
})
结果:
调用transformToTree()自定义父节点树形名称
点击查看代码
// 修改父节点 属性名
listSmalls().then(data => {
this.depts = transformToTree(data, { parentKey: 'pid' })
console.log(this.depts)
})
三、遇到的报错
四、参考博客
本文作者:独而不孤
本文链接:https://www.cnblogs.com/lcaiqin/p/17717743.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步