[英]How to get nested parent path from a JSON tree in JavaScript?
我有一個像這樣的 JSON 樹結構。
[
{
"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"
}
]
}
]
}
]
我想要的是當我將“東北”傳遞給函數()時,它應該從根返回點符號字符串路徑。 在這種情況下,函數的預期返回字符串將是“links.world.usa.northeast”
您可以測試每個嵌套數組,如果找到,則將每個級別的id
作為路徑。
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'));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.