<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<script>
// 1. 数组转树形数据
const array = [
{
id: 2,
pid: 1,
},
{
id: 3,
pid: 1,
},
{
id: 4,
pid: 2,
},
{
id: 5,
pid: 3,
},
{
id: 6,
pid: 4,
},
]
function ArrToTreeData(data, parentId) {
//定义个空数组接收参数
var arr = []
data.forEach((item) => {
if (item.pid === parentId) {
// 找到之后 就要去找 item 下面有没有子节点
//条件不能是(data, parentId),否则死递归
const children = ArrToTreeData(data, item.id)
if (children.length) {
// 如果children的长度大于0 说明找到了子节点
item.children = children
}
arr.push(item) // 把找到的数据内容加入到数组中
}
})
//返回这个数组
return arr
}
const treeData = {
id: 1,
pid: null,
children: [],
}
treeData.children = ArrToTreeData(array, treeData.id)
console.log('treeData', treeData)
function treeToArr(data, res = []) {
data.forEach((item) => {
res.push(item)
if (item.children && item.children.length !== 0) {
treeToArr(item.children, res)
}
})
return res
}
treeToArr(tree)
// 2.树形转数组结构
const tree = [
{
id: 1,
pid: null,
children: [
{
id: 2,
pid: 1,
children: [
{
id: 4,
pid: 2,
children: [
{
id: 6,
pid: 4,
},
],
},
],
},
{
id: 3,
pid: 1,
children: [
{
id: 5,
pid: 3,
},
],
},
],
},
]
console.log('arrayData', treeToArr(tree))
</script>
</body>
</html>
|