构造了一个父子树,想获取某个节点的路径,可是获取不了,不知道哪里出错,求解。
var data = [{
'id': 'root',
'text': 'Root',
'children': [{
'id': 1,
'text': 'Child 1'
}, {
'id': 2,
'text': 'Child 2',
'children': [{
'id': 6,
'text': 'Child 6'
}, {
'id': 7,
'text': 'Child 5',
'children': [
]
}]
}]
}];
var tree = function(data) {
this.data = data;
}
tree.prototype = {
init: function(tree, nodeParent) {
var _this = this;
tree = tree || this.data;
if (tree && Array.isArray(tree)) {
tree.forEach(function(node, index) {
node.parent = nodeParent;
if (node.children && Array.isArray(node.children)) {
_this.init(node.children, node);
}
})
}
},
get_path: function(node, path) {
path = path || "";
if (node.parent) {
path = node.text + ' >> ' + path;
this.get_path(node.parent, path);
} else {
return path;
}
console.log(path); // Child 2 >> Child 6 >>
},
// 遍历树
traverse: function(tree, fn) {
var _this = this;
tree = tree || this.data;
if (tree && Array.isArray(tree)) {
tree.forEach(function(node, index) {
fn && fn.call(_this, node, tree, index);
if (node && node.children && Array.isArray(node.children)) {
_this.traverse(node.children, fn);
}
})
} else {
fn.call(_this, tree);
}
},
_get: function(id, fn) {
var _this = this;
var found = false;
this.traverse(this.tree, function(node, tree, index) {
if (node.id === id) {
found = node;
fn && fn.call(_this, node, tree, index);
}
})
if (!found) {
throw new Error("can get node id " + id);
}
return found;
},
};
var mytree = new tree(data);
mytree.init();
console.log(mytree.get_path(mytree._get(6)));
使用上面的get_path递归方法,最后root节点的引用失效了(可能是有Circular相互引用导致),下面的函数有效。
get_path: function(node, path) {
console.log(node);
console.log("-".repeat(10));
path = path || "";
while(node.parent) {
path = node.text +' >> ' + path;
node = node.parent;
}
path = node.text +' >> ' + path; // ROOT
return path;
},
或许应该避免循环引用,只保留父节点的id,获取路径。(效率不高)
init: function(tree, nodeParent) {
var _this = this;
tree = tree || this.data;
if (tree && Array.isArray(tree)) {
tree.forEach(function(node, index) {
node.parent = nodeParent && nodeParent.id ? nodeParent.id : undefined;
if (node.children && Array.isArray(node.children)) {
_this.init(node.children, node);
}
})
}
},
get_path: function(node) {
path = [], parent;
while(node.parent) {
parent = this._get(node.parent);
path.push(parent);
node = parent;
}
return path.reverse();
},