We often encountered in actual business scenarios work in such a scene, obtaining data tree node in a node, and the father of all father nodes, such a scenario is not recommended depth traversal, using breadth traversal can be found more quickly.
1, Case Commentary
For example, the tree looks like this:
Data Tree is this:
Is our common data and appearance of the tree.
2, business requirements
[5] In the extraction test behind a new node requires
1) the incoming interface requires the parent of the current node;
2) after the new reacquisition tree data, expanded by default all of the parent
3, and description code implementation
Ideas:
1) setting a line array parentIdsQueue
will start queuing tree data;
2) if the current node has children, the child nodes descending added to the queue, because the time is traversed from the start of the first data;
3) if the current data have children nodes before children queued data into the parent node parentArr
; and
4) If a node is found, if the node is the first layer, can be directly obtained; if included parentArr
, is parentArr
in all its parent level node
More than just words to the implementation code
// id 指的是当前点击的节点id;
findParentNode (id) {
// 初始化所需数据
this.firstParentObj = {}; // 记录直系父级的名称和id即接口要传的数据
this.parentIds = []; // 记录所有的父级ids
this.parentIdsQueue = []; // 记录排队的
// 将树放到排队系列
this.parentIdsQueue = this.treeData;
// 开始遍历排队的树
while (this.parentIdsQueue.length) {
//抽取第一个排队的数据
let item = this.parentIdsQueue.shift();
let { children } = item;
if (item.id === id) {
// 第一层就找到了
if (!item.parentArr) {
this.firstParentObj = {
id: item.id,
name: item.title
};
this.parentIds = [item.id];
} else {
// 获取当前节点的parentArr
let len = item.parentArr.length;
this.firstParentObj = item.parentArr[len - 1];
item.parentArr.forEach(a => {
this.parentIds.push(a.id);
});
this.parentIds.push(item.id);
}
// 结束遍历
this.parentIdsQueue = [];
break;
} else if (children && children.length) {
let len = children.length;
for (let i = len - 1; i >= 0; i--) {
// 新建一个数组用于记录它的父亲节点
children[i].parentArr = [];
// 把它的历史父亲节点们先放入
if (item.parentArr) {
children[i].parentArr = children[i].parentArr.concat(
item.parentArr
);
}
// 再放入当前的父亲节点
children[i].parentArr.push({
id: item.id,
name: item.title
});
// 加入到排队序列中
this.parentIdsQueue.unshift(children[i]);
}
}
}
}
5 results presentation
We add nodes in the example cited in the text before, are now required to print out the data
console.log("测试抽取5的所有父亲",item.parentArr);
console.log("接口所需的父亲节点数据",this.firstParentObj);
console.log("设置树展开所需的所有父亲节点数据节点id", this.parentIds);
As shown, we have achieved related functions. As to expand the tree, all the parent node acquired id traverse the tree in parentIds
settings that expand
is true can be.