const treeData = [
{
title: '1',
id: '1',
key: '1',
children: [
{
title: '1-1',
id: '2',
key: '2',
children: [
{
title: '1-1-1',
id: '3',
key: '3',
},
],
},
],
},
{
title: '2',
id: '2',
key: '1',
children: [
{
title: '2-1',
id: '4',
key: '4',
children: [
{
title: '2-1-1',
id: '5',
key: '5',
},
],
},
],
},
];
export function findSons(tree, nodeId) {
for (let item of tree) {
if (item.id === nodeId) {
return item.children || [];
} else if (item.children && item.children.length > 0) {
let r = findSons(item.children, nodeId);
if (r.length > 0) {
return r;
}
}
}
return [];
}
- 根据某一节点id 递归查找父节点 与其自身 返回 ids 数组
export function findParents(tree, id) {
for (let i in tree) {
if (tree[i].id == id) return [tree[i].id];
if (tree[i].children) {
let node = findParents(tree[i].children, id);
if (node !== undefined) return node.concat(tree[i].id);
}
}
}
export function rightTreeDataFilter(allTreeData, keys = [], res = []) {
for (let item of allTreeData) {
if (keys.includes(item.key)) {
let one = { ...item };
one.children = [];
if (item.children && item.children.length > 0) {
rightTreeDataFilter(item.children, keys, one.children);
}
res.push(one);
}
}
}
export function countLength(allTreeData, count) {
for (let item of allTreeData) {
count.number++;
count.ids.push(item.id);
if (item.children && item.children.length > 0) {
countLength(item.children, count);
}
}
}
export function filterTree(treeData, searchString) {
let result = [];
function traverse(node) {
if (node.title.includes(searchString)) {
result.push(node);
} else {
if (node.children && node.children.length > 0) {
node.children.forEach((child) => {
traverse(child);
});
}
}
}
for (let item of treeData) {
traverse(item);
}
return result;
}
export function filterTreeAndFather(treeData, searchString) {
function checkNodeAndSubtree(node) {
if (node.title.includes(searchString)) {
return true;
} else if (node.children) {
let hasMatchingChild = false;
node.children = node.children.filter((child) => {
const result = checkNodeAndSubtree(child);
if (result) hasMatchingChild = true;
return result;
});
return hasMatchingChild;
}
return false;
}
return treeData.filter((rootNode) => checkNodeAndSubtree(rootNode));
}