const tree = [
{
id: '1',
name: '营销体系',
children: [
{
id: '1-1',
name: '营销体系-南区开发团队'
}
]
},
{
id: '2',
name: '交付体系'
}
]
const findNodeById = (nodes, id) => {
for (const node of nodes) {
// 找到目标节点,直接返回,递归结束
if (node.id === id) {
// 这里会有两种情况:
// 1. 如果这里不是在递归中,node会作为调用处的返回值,函数结束
// 2. 如果这里是在递归中,node会作为递归调用处的返回值(赋值给foundNode的地方),当前层的递归结束
return node
}
// 未找到目标节点,如果存在children,则将其作为nodes和原始id一起递归调用findNodeById
if (node.children) {
const foundNode = findNodeById(node.children, id)
// 找到目标节点,直接返回,递归结束
if (foundNode) {
return foundNode
}
}
}
// 未目标节点,递归结束
return null
}
const res = findNodeById(tree, '1-1');
console.log(res);
// {"id":"1-1","name":"营销体系-南区开发团队"}