我有一个像这样的 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"
}
]
}
]
}
]
我想要的是,当我将“northeast”传递给 function() 时,它应该返回我从根开始的点符号字符串路径。在这种情况下,函数的预期返回字符串将为“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'));
关于javascript - 如何在 JavaScript 中从 JSON 树获取嵌套父路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59713227/