麻烦帮忙写个方法,关于多维数组递归问题?-灵析社区

文文问问

const id = 88 const arr = [ { text: '第一层', id: 1, children: [ { text: '第二层', id: 2, children: [ { text: '第三层', id: 88 } ] } ] }, { text: '第一层', id: 3, children: [ { text: '第二层', id: 4, children: [ { text: '第三层', id: 5 } ] } ] } ] function getIds(id) // ['1,2,88'] 要求写一个方法,匹配上id后,联同祖类所有的id都获取到放到数组返回

阅读量:13

点赞量:0

问AI
需要封装一个递归函数(已去除undefined): function findPathById(tree, targetId) { let path = []; function traverse(node, currentPath) { if (node.id === targetId) { path = [...currentPath, node.id]; return true; // 当找到目标 ID 时返回 true } if (node.children) { for (let child of node.children) { if (traverse(child, [...currentPath, node.id])) { return true; // 如果在子节点中找到目标 ID,则返回 true } } } return false; } for (let node of tree) { if (traverse(node, [])) { break; // 当找到目标 ID 时停止遍历 } } return path; } 传入数组和要查找的id值,如下: findPathById(arr,88)