I have a JSON tree structure like this.
[
{
"title":"News",
"id":"news"
},
{
"title":"Links",
"id":"links",
"children":[
{
"title":"World",
"id":"world",
"children":[
{
"title":"USA",
"id":"usa",
"children":[
{
"title":"Northeast",
"id":"northeast"
},
{
"title":"Midwest",
"id":"midwest"
}
]
},
{
"title":"Europe",
"id":"europe"
}
]
}
]
}
]
What i want is when i pass "northeast" to a function() it should return me the dot notation string path from the root. Expected return string from the function in this case would be "links.world.usa.northeast"
You could test each nested array and if found, take the id
from every level as path.
const pathTo = (array, target) => {
var result;
array.some(({ id, children = [] }) => {
if (id === target) return result = id;
var temp = pathTo(children, target)
if (temp) return result = id + '.' + temp;
});
return result;
};
var data = [{ title: "News", id: "news" }, { title: "Links", id: "links", children: [{ title: "World", id: "world", children: [{ title: "USA", id: "usa", children: [{ title: "Northeast", id: "northeast" }, { title: "Midwest", id: "midwest" }] }, { title: "Europe", id: "europe" }] }] }];
console.log(pathTo(data, 'northeast'));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With