题意描述
有如下的部门信息数据,id表示部门id,pid表示上级部门的id,最高级的部门为部门0,现在要将下面的部门列表转为树形结构。
let list = [
{ id: 1, name: '部门1', pid: 0 },
{ id: 2, name: '部门2', pid: 1 },
{ id: 3, name: '部门3', pid: 1 },
{ id: 4, name: '部门4', pid: 3 },
{ id: 5, name: '部门5', pid: 4 },
{ id: 6, name: '部门6', pid: 0 },
{ id: 0, name: '部门0' }
]
递归实现
- 找出列表中的根节点
- 递归的在列表中找出每个节点的子节点
- 返回根节点的子节点数组
/**
* 返回一个数组,表示root.children
* @param {array} rootList
* @param {string} id
* @param {array} list
* @return {array}
*/
function getTreeList(rootList, id, list) {
for (const item of rootList) {
if (item.pid === id) {
list.push(item)
}
}
for (const item of list) {
item.children = []
getTreeList(rootList, item.id, item.children)
if (item.children.length === 0) {
delete item.children
}
}
return list
}
/**
1. 返回树形结构
2. @param {Array<Object>} rootList
3. @return {Object}
*/
function getTreeData(rootList) {
const root = rootList.find((item) => !item.hasOwnProperty('pid'))
const rootChildren = getTreeList(rootList, root.id, [])
return {
...root,
children: rootChildren
}
}
测试
let treeData = getTreeData(list)
console.log(JSON.stringify(treeData));
结果
{
"id": 0,
"name": "部门0",
"children": [
{
"id": 1,
"name": "部门1",
"pid": 0,
"children": [
{
"id": 2,
"name": "部门2",
"pid": 1
},
{
"id": 3,
"name": "部门3",
"pid": 1,
"children": [
{
"id": 4,
"name": "部门4",
"pid": 3,
"children": [
{
"id": 5,
"name": "部门5",
"pid": 4
}
]
}
]
}
]
},
{
"id": 6,
"name": "部门6",
"pid": 0
}
]
}
非递归方法
- 遍历列表
- 对于列表的每一项,再去遍历一遍列表,筛选出其子节点,同时找出根节点
- 返回根节点
/**
* 返回树形结构
* @param {Array<Object>} rootList
* @return {Object}
*/
function getTreeData_2(rootList) {
let root = null
for (const item of rootList) {
const children = rootList.filter((ele) => ele.pid === item.id)
if (children.length) {
item.children = children
}
if (item.pid === undefined) {
root = item
}
}
return root
}
1万+

被折叠的 条评论
为什么被折叠?



