将 list 数据组装成 tree 数据格式
1. pid 为父节点id, self 为本身节点id
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
</body>
</html>
<script>
var arrlist = [
{ id: 1, pid: '', self: 's_01' },
{ id: 2, pid: 's_01', self: 's_02' },
{ id: 3, pid: 's_01', self: 's_03' },
{ id: 4, pid: 's_02', self: 's_04' },
{ id: 5, pid: 's_03', self: 's_05' },
{ id: 6, pid: 's_02', self: 's_06' },
{ id: 7, pid: 's_02', self: 's_07' },
{ id: 8, pid: 's_03', self: 's_08' },
{ id: 9, pid: 's_03', self: 's_09' },
{ id: 10, pid: 's_03', self: 's_10' },
{ id: 11, pid: 's_03', self: 's_11' },
{ id: 12, pid: 's_03', self: 's_12' },
{ id: 13, pid: 's_03', self: 's_13' },
{ id: 14, pid: 's_06', self: 's_14' },
{ id: 15, pid: 's_06', self: 's_15' },
{ id: 16, pid: 's_06', self: 's_16' },
{ id: 17, pid: 's_06', self: 's_17' },
{ id: 18, pid: 's_06', self: 's_18' },
{ id: 19, pid: 's_06', self: 's_19' },
{ id: 20, pid: 's_06', self: 's_20' },
];
// 过滤所有根节点
var tree = arrlist.filter(el => el.pid == '');
// arr 原始数据 itemdata 当前节点
function transformData(arr, itemdata) {
let temp = [];
itemdata.children = [];
for (let index = 0; index < arr.length; index++) {
const el = arr[index];
if (itemdata.self == el.pid) {
temp.push(el);
itemdata.children.push(el);
}
}
// 递归调用
if (temp.length != 0) {
for (let index = 0; index < itemdata.children.length; index++) {
const el = itemdata.children[index];
transformData(arrlist, el);
}
}
}
// 为每个根节点,添加子元素
tree.forEach(el => {
transformData(arrlist, el);
})
console.log('arrlist 原始数据 =', arrlist);
console.log('arrlist 转化后的 =', tree);
</script>