在前些天的时候分享了一个# 使用JS求解树的根节点到指定节点的路径的方法,后面用的时候发现扩展性不强,而且限定在vue的使用环境中,遂进行优化,写成独立的JS工具函数。同时分享一个我老大写的功能相近的函数。
我的优化后的代码
/*
* treeData<Array>: 树形数据
* currKey<Number>: 查找的key值
* valueKey<String>: 需要查找的数据
* return <Arrary> 从根节点到当前节点的指定值(valueKey)组成的数组
*/
const getFullName = (treeData, currKey, valueKey = "name") => {
if (!Array.isArray(treeData)) return "";
// 为节点添加parentId,并维护id节点对象方便查找
function addParent(tree = [], pId) {
if (!Array.isArray(tree)) return;
tree.forEach((item, index, arr) => {
arr[index]["_parentId"] = pId;
map.set(item?.id, item); // 全局变量new Map()
if (item?.children) {
addParent(item.children, item.id);
} else {
return;
}
});
}
// 递归查找父节点的值
function reTree(key, map) {
let node = map.get(key);
if (!node) return;
let pid = node._parentId;
fullPath.unshift(node[valueKey]);
reTree(pid, map);
}
let data = JSON.parse(JSON.stringify(treeData));
let map = new Map();
let fullPath = [];
addParent(data, "null");
reTree(currKey, map);
return fullPath;
};
另一种方法
const getTreeNodePathBykey = (nodes, value, key = 'id') => {
if (!(nodes && nodes.length)) return [];
const path = [];
function fn(node) {
path.push(node[key]);
console.log(path);
if (node[key] === value) {
throw 'over';
}
if (node.children && node.children.length) {
node.children.forEach(subNode => {
fn(subNode);
});
// 当前子节点遍历完,没有符合的,移除当前路径
path.pop();
} else {
// 找到叶子节点时,移除该叶子节点
path.pop();
}
}
try {
nodes.forEach(node => {
fn(node);
});
} catch (e) {
return path;
}
};
通过解决算法问题,可以有效的提高自身的编程水平。而在同一个问题往往有很多种求解方法,多学习多积累。