在json树中查找值并返回路径

时间:2016-05-26 12:26:15

标签: javascript

我有子数据,我必须按名称查找元素并打印元素的路径。我写了搜索功能,找到了元素,但无法处理PATH。我应该在哪里处理它?如何在搜索时添加或删除路径?

 let data = {
type: "folder",
name: "animals",
children: [
    {
        type: "folder",
        name: "cat",
        children: [
            {
                type: "folder",
                name: "images",
                children: [
                    {
                        type: "file",
                        name: "cat001.jpg"
                    }, {
                        type: "file",
                        name: "cat002.jpg"
                    }
                ]
            },
            {
                type: "folder",
                name: "images",
                children: [
                    {
                        type: "file",
                        name: "cat001.jpg"
                    }, {
                        type: "file",
                        name: "cat002.jpg"
                    }
                ]
            }
        ]
    },
    {
        type: "folder",
        name: "dog",
        children: [
            {
                type: "folder",
                name: "images",
                children: [
                    {
                        type: "file",
                        name: "dog001.jpg"
                    }, {
                        type: "file",
                        name: "dog002.jpg"
                    }
                ]
            }
        ]
    },
    {
        type: "file",
        name: "horse.png"
    },
    {
        type: "file",
        name: "bear.png"
    },
    {
        type: "file",
        name: "horse.png"
    }
]

};

search(data, name, path = "") {
    if (data.name == name) {
        let path = [data.name];
        return path;
    } else if (data.children != null) {
        let result = null;
        for (let i = 0; result == null && i < data.children.length; i++) {
            result = this.search(data.children[i], name);
        }
        return result;
    }
    return null;
}

1 个答案:

答案 0 :(得分:1)

只要您找到了一些内容,就可以添加到路径中:

… if (data.children != null) {
    for (let i = 0; i < data.children.length; i++) {
        let result = this.search(data.children[i], name);
        if (result) {
            result.unshift("children", i); // or whatever you want in your path
            return result;
        }
    }
}