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

作者站长头像
站长
· 阅读数 8
        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都获取到放到数组返回

回复
1个回答
avatar
test
2024-06-26

需要封装一个递归函数(已去除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)

回复
likes
适合作为回答的
  • 经过验证的有效解决办法
  • 自己的经验指引,对解决问题有帮助
  • 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
  • 询问内容细节或回复楼层
  • 与题目无关的内容
  • “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容