RaShe RaShe - 6 months ago 16
Javascript Question

Find value in json tree and return the path

I have data with children, i have to find element by name and print the path to element. I wrote search fucntion that finds the element, but can't handle with PATH. Where i should handle it? How to add or remove path while searching?

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;
}

Answer

Just add to the path once you've found something:

… 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;
        }
    }
}
Comments