首页 > 解决方案 > 在JS中递归搜索嵌套数组

问题描述

我正在尝试在嵌套的 json 数组中搜索具有匹配名称的单个对象。我的数据结构如下所示:

[
    {
        "type": "directory",
        "name": "/home/user/test-tree",
        "contents": [
            {
                "type": "directory",
                "name": "my-folder",
                "contents": [
                    {
                        "type": "directory",
                        "name": "nested-folder",
                        "contents": []
                    }
                ]
            },
            {
                "type": "directory",
                "name": "node_modules",
                "contents": [
                    {
                        "type": "directory",
                        "name": "gunzip-file",
                        "contents": []
                    }
                ]
            }
        ]
    }
]

所以在这个例子中,我可能正在搜索一个名为“node_modules”的目录,它应该返回整个对象,包括它的内容。这只是一个示例,我的实际数据集可能非常大 - 例如,树可以代表文件系统上的所有目录。

这是我现在正在使用的代码 - 它似乎适用于这个示例,但它似乎不适用于更大的数据集,而且我真的看不出它有什么问题,所以如果有人能发现任何我会很感激的。

    function treeSearch(array, dirName) {
        for (let i = 0; i < array.length; i++) {
            if (array[i].name === dirName) {
                return array[i]
            }
            else if (array[i].contents) {
                if (array[i].contents.length > 0) {
                    return treeSearch(array[i].contents, dirName)
                }
            }
        }
    }

标签: javascript

解决方案


如果找到值,您可以采用递归函数迭代数组,并可能出现短路。

function find(array, value) {
    var result;
    array.some(o => result = o.name === value && o || find(o.contents, value));
    return result || undefined;
}

var data = [{ type: "directory", name: "/home/user/test-tree", contents: [{ type: "directory", name: "my-folder", contents: [{ type: "directory", name: "nested-folder", contents: [] }] }, { type: "directory", name: "node_modules", contents: [{ type: "directory", name: "gunzip-file", contents: [] }] }] }]

console.log(find(data, "node_modules"));
.as-console-wrapper { max-height: 100% !important; top: 0; }


推荐阅读