varnodes=[{id:1,name:1,children:[{id:4,name:4}]}]实现方式//递归实现//@leafId查找的id,//@nodes原始Json数据//@path供递归使用functionfindPathByLeafId(leafId,no
var nodes = [{id:1,name:1,children:[{id:4,name:4}]}]
实现方式
//递归实现
//@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))
function findPathByLeafId(leafId, nodes, path){
if(path === undefined) {
path = {};
}
for(var i = 0; i < nodes.length; i++) {
var tmpPath = path;
// tmpPath.push(nodes[i].id);
if(leafId == nodes[i].id) {
tmpPath=nodes[i];
return tmpPath;
}
if(nodes[i].children) {
var findResult = findPathByLeafId(leafId, nodes[i].children, tmpPath);
if(findResult) {
return findResult;
}
}
}
}