方法1:递归
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<script>
let arr = [
{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}
]
function getChildren (data, result, pid) {
for (const item of data) {
if (item.pid === pid) {
const newItem = {...item, children: []}
result.push(newItem)
getChildren(data, newItem.children, item.id)
}
}
}
const arrayToTree = (data, pid) => {
const result = []
getChildren(data, result, pid)
return result
}
let res = arrayToTree(arr, 0)
console.log(res)
</script>
</body>
</html>
哎不理解 但是这个只支持两层,递归的都可以
return arr.map((item, index) => {
item.children = arr.filter(v => v.pid === item.id)
return item
})[0]
let arr = [
{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: 5}
]
function arrayToTree (items) {
const result = []
const itemMap = {}
for (const item of items) {
itemMap[item.id] = {...item, children: []}
}
for (const item of items) {
const id = item.id
const pid = item.pid
const treeItem = itemMap[id]
if (pid === 0) {
result.push(treeItem)
} else {
if (!itemMap[pid]) {
itemMap[pid] = {
children: []
}
}
itemMap[pid].children.push(treeItem)
}
}
return result
}
let res = arrayToTree(arr)
console.log(res)
|