list转树方法
js
const oldData = [
{
"DeptID": 1,
"DeptNo": "00001",
"DeptName": "防辐射技术有限公司",
"FatherID": 0
},
{
"DeptID": 2,
"DeptNo": "00002",
"DeptName": "财务部",
"FatherID": 1
},
{
"DeptID": 3,
"DeptNo": "00003",
"DeptName": "生产部",
"FatherID": 2
},
{
"DeptID": 4,
"DeptNo": "00004",
"DeptName": "销售部",
"FatherID": 1
},
{
"DeptID": 5,
"DeptNo": "00005",
"DeptName": "行政部",
"FatherID": 1
},
{
"DeptID": 6,
"DeptNo": "00006",
"DeptName": "人事部",
"FatherID": 5
},
{
"DeptID": 7,
"DeptNo": "00007",
"DeptName": "研发中心",
"FatherID": 1
},
{
"DeptID": 8,
"DeptNo": "00008",
"DeptName": "产品部",
"FatherID": 7
},
{
"DeptID": 9,
"DeptNo": "00009",
"DeptName": "研发部",
"FatherID": 7
},
{
"DeptID": 10,
"DeptNo": "00010",
"DeptName": "硬件部",
"FatherID": 7
},
{
"DeptID": 31,
"DeptNo": null,
"DeptName": "销售王牌",
"FatherID": 4
},
{
"DeptID": 32,
"DeptNo": null,
"DeptName": "销售1+1",
"FatherID": 4
},
{
"DeptID": 33,
"DeptNo": null,
"DeptName": "销售1+1+1",
"FatherID": 32
}
]
function listToTree(list) {
var map = {}, node, tree= [], i;
for (i = 0; i < list.length; i ++) {
map[list[i].FatherID] = list[i];
list[i].children = [];
}
for (i = 0; i < list.length; i += 1) {
node = list[i];
if (node.DeptID === node.FatherID) {
map[node.FatherID].children.push(node);
} else {
tree.push(node);
}
}
return tree;
}
console.log(listToTree(oldData))
// 注 : list 传来的数组 , value 筛选的条件
function arrToTree(list, value) {
// 1.定义一个空数组,后续往里面添加树形结构
const arr = []
list.forEach(item => {
// 2. 筛选满足要求的item
if (item.pid === value) {
// 3.筛选所有孩子,即pid与父级id一致的(外循环走一次,里面走完所有)
const children = arrToTree(list, item.id)
// 4.父级中有孩子,才能加上children属性
if (children.length > 0) {
// 5. 因为需要的树形结构中孩子属性名为children,手动给父级添加一个children属性,并赋值
item.children = children
}
// 6. 把满足要求的一组数据push进去
arr.push(item)
}
})
// 返回树形结构
return arr
}
排序方法
js
let nums=[1,5,6,4,5,56,91,21,34,52,58,7,9,41,32,10,3,3]
for (let i = 0, len = nums.length;i<len; i++) {
for (let j = i + 1; j < len; j++) {
if (nums[i] > nums[j]) {
[nums[i], nums[j]] = [nums[j], nums[i]]
}
}
}
console.log(nums)
递归删除树中的空节点
- 方式一
js
function deleteGroup(treeArr: any[]) {
function traversal(data:any[]) {
for (let i = 0; i < data.length; i++) {
const info = data[i]
if (info.children) {
if (info.children.length > 0) {
traversal(info.children)
}
if (info.children.length === 0) {
data.splice(i, 1)
//
i--
}
}
}
}
traversal(treeArr)
}
- 方式二
js
function deleteGroup(treeArr: any[]) {
treeArr = treeArr.filter(node => {
if (node.children) {
node.children = deleteGroup(node.children);
return node.children.length > 0;
}
return true;
});
return treeArr;
}
deleteGroup(treeData)