1 回答

TA貢獻1786條經驗 獲得超13個贊
很多人都在抱怨你沒有把代碼貼出來,能回答問題的人可都是真心的!
簡化版實驗原始數據(也供其他人可以驗證自己的方案)
var nodes = [
{
"id": 1,
"children": [
{
"id": 3,
"children": [
{"id": 4},
{"id": 9}
]
},
{
"id": 10
},
]
},
{
"id": 2
},
{
"id": 6,
"children" : [
{ "id": 5},
{ "id": 7},
{ "id": 8}
]
}
];
JS查找輸出結果
//遞歸實現
//@leafId 為你要查找的id,
//@nodes 為原始Json數據
//@path 供遞歸使用,不要賦值
function findPathByLeafId(leafId, nodes, path) {
if(path === undefined) {
path = [];
}
for(var i = 0; i < nodes.length; i++) {
var tmpPath = path.concat();
tmpPath.push(nodes[i].id);
if(leafId == nodes[i].id) {
return tmpPath;
}
if(nodes[i].children) {
var findResult = findPathByLeafId(leafId, nodes[i].children, tmpPath);
if(findResult) {
return findResult;
}
}
}
}
//用法
console.log(findPathByLeafId(4, nodes)); //輸出 [1,3,4]
console.log(findPathByLeafId(9, nodes)); //輸出 [1,3,9]
console.log(findPathByLeafId(7, nodes)); //輸出 [6,7]
添加回答
舉報