数据源
[
{
"id": 1,
"name": "办公管理",
"pid": 0,
"children": [
{
"id": 2,
"name": "请假申请",
"pid": 1,
"children": [
{
"id": 4,
"name": "请假记录",
"pid": 2
}
]
},
{
"id": 3,
"name": "出差申请",
"pid": 1
}
]
},
{
"id": 5,
"name": "系统设置",
"pid": 0,
"children": [
{
"id": 6,
"name": "权限管理",
"pid": 5,
"children": [
{
"id": 7,
"name": "用户角色",
"pid": 6
},
{
"id": 8,
"name": "菜单设置",
"pid": 6
}
]
}
]
}
]
递归函数
function getChildrenById(dataSource, id) {
// hasFound 表示是否有找到id值
let [hasFound, result] = []
function findById(data) {
if (Array.isArray(data) && !hasFound) { // 判断是否是数组并且没有的情况下,
data.forEach(item => {
if (item.id === id) { // 数据循环每个子项,并且判断子项下边是否有id值
result = item; // 返回的结果等于每一项
hasFound = true; // 并且找到id值
}
else if (item.children) {
findById(item.children); // 递归调用下边的子项
}
})
}
}
findById(dataSource); // 调用一下
return result;
}
for of优化递归
export const getChildrenById = (dataSource = [], id) => {
let result;
function findById(data) {
if(result) break; // 核心点,不然会有多余的渲染
// 判断是否是数组并且,数组有长度
if (Array.isArray(data)) {
for (const item of data) {
// 数据循环每个子项,并且判断子项下边是否有id值
if (item.id === id) {
result = item; // 返回的结果等于每一项
break;
} else if (Array.isArray(item.children)) {
findById(item.children); // 递归调用下边的子项
}
}
}
}
findById(dataSource); // 调用一下
return result;
};