数组转树
// 元数据
const currentArray = [
{id:"01", name: "张大大", pid:"", job: "项目经理"},
{id:"02", name: "小亮", pid:"01", job: "产品leader"},
{id:"03", name: "小美", pid:"01", job: "UIleader"},
{id:"04", name: "老马", pid:"01", job: "技术leader"},
{id:"05", name: "老王", pid:"01", job: "测试leader"},
{id:"06", name: "老李", pid:"01", job: "运维leader"},
{id:"07", name: "小丽", pid:"02", job: "产品经理"},
{id:"08", name: "大光", pid:"02", job: "产品经理"},
{id:"09", name: "小高", pid:"03", job: "UI设计师"},
{id:"10", name: "小刘", pid:"04", job: "前端工程师"},
{id:"11", name: "小华", pid:"04", job: "后端工程师"},
{id:"12", name: "小李", pid:"04", job: "后端工程师"},
{id:"13", name: "小赵", pid:"05", job: "测试工程师"},
{id:"14", name: "小强", pid:"05", job: "测试工程师"},
{id:"15", name: "小涛", pid:"06", job: "运维工程师"}
];
方法一:递归
function arrToTree(list, pid){
let flag = list.filter(item => item.pid === pid); // 1
return flag.length === 0 ? [] : flag.map(i => { // 2
let obj = {label: i.name, children: arrToTree(list, i.id)};
return obj.children.length === 0 ? { label: obj.label } : obj // 3
})
}
arrToTree(currentArray, '');
方法二:非递归(只适用于js)
// 巧妙的应用了对象保存的是引用的特点
// 代码少,性能不如下面
function arrToTree(data) {
const result = []
data.forEach(item =>{
const parent = data.find(i => i.id === item.pid)
if (parent) {
parent['children'] = [...(parent['children'] ?? []), item]
} else {
result.push(item);
}
});
return result;
}
// 性能提升版
function arrToTree(data) {
const result = []
const map = {}
data.forEach(item => map[item.id] = item)
data.forEach(item =>{
const parent = map[item.pid]
if (parent) {
parent['children'] = [...(parent['children'] ?? []), item]
} else {
result.push(item);
}
});
return result;
}
树转数组
let JsonTree = [
{id: 1, title: '解忧杂货铺1', pid: 0},
{
id: 2, title: '解忧杂货铺2', pid: 0, children: [
{id: 6, title: '解忧杂货铺4-2', pid: 2},
{
id: 3, title: '解忧杂货铺2-1', pid: 2, children: [
{
id: 4, title: '解忧杂货铺3-1', pid: 3, children: [
{id: 5, title: '解忧杂货铺4-1', pid: 4},
]
},
]
},
]
}
];
方法一: 递归
function flatten(data) {
return data.reduce((arr, {id, title, pid, children = []}) =>
arr.concat([{id, title, pid}], flatten(children)), []);
}
let flatArr = flatten(JsonTree);
树过滤
export interface DepartmentChildren extends API.department {
title: string
value: string
children?: DepartmentChildren[]
}
export const treeFilter = (tree: DepartmentChildren[], func: Function): DepartmentChildren[] => {
// 使用map复制一下节点,避免修改到原树
return tree.map(node => ({ ...node })).filter(node => {
node.children = node.children && treeFilter(node.children, func)
return func(node) || (node.children && node.children.length)
})
}