// 代码
export function getParent(data, nodeId,nodeName) {
const query = nodeId;
const json = data;
let parentNode = null;
let node = null;
const getNode = (json, id) => {
// 1.第一层 root 深度遍历整个JSON
for (let i = 0; i < json.length; i++) {
if (node) {
break;
}
const obj = json[i];
// 没有就下一个
if (!obj || !obj.id) {
continue;
}
// 2.有节点就开始找,一直递归下去
if (obj.id === id) {
// 找到了与name匹配的节点,结束递归
node = obj;
break;
} else {
// 3.如果有子节点就开始找
if (obj.children && obj.children.length !== 0) {
// 4.递归前,记录当前节点,作为parent 父亲
parentNode = obj;
// 递归往下找
getNode(obj.children, id);
} else {
// 跳出当前递归,返回上层递归
continue;
}
}
}
// 5.如果木有找到父节点,置为null,因为没有父亲
if (!node) {
parentNode = null;
}
// 6.返回结果obj
return {
parentNode,
node
};
}
// 批量查询
const result = [];
const getResult = function (json, query) {
node = null;
parentNode = null;
const obj = getNode(json, query);
// 判断是否闭包
if (obj.parentNode) {
// 有父节点
// 获取父节点name继续查祖节点
getResult(json, obj.parentNode.id);
result.push(obj.parentNode.name);
}
return result;
}
getResult(json, query);
// 最后将查询push到result中
result.push(nodeName);
return result
}
使用:
getParent(data, query.id, query.name)// data数据源 ,query.id传入的id,query.name传入的name
使用场景:
点击指标拆解,显示相应路径