export function getChildren(val, tree, key = 'dbid') {
let hasFound = false;
let result = null;
const fn = (data) => {
if (Array.isArray(data) && !hasFound) {
data.forEach((item) => {
if (item[key] === val) {
result = item;
hasFound = true;
} else if (item.children) {
fn(item.children);
}
});
}
};
fn(tree);
return result;
}
export function getTrajectory(dataList) {
let treePath = '';
dataList.forEach(item => (treePath = `${treePath}/${item.nameZh}`));
return treePath.substring(1);
}
export function getAllLeafNode(tree, key = 'dbid') {
const val = [];
const mapTree = (node, innerVal, innerKey) => {
node.forEach((item) => {
if (!item.children) {
innerVal.push(item[innerKey]);
} else {
mapTree(item.children, innerVal, innerKey);
}
});
};
mapTree(tree, val, key);
return val;
}
export function getTreeAppointField(tree, key = 'dbid') {
const val = [];
const mapTree = (node, innerVal, innerKey) => {
node.forEach((item) => {
innerVal.push(item[innerKey]);
if (item.children) {
mapTree(item.children, innerVal, innerKey);
}
});
};
mapTree(tree, val, key);
return val;
}
export function treeTraversalToAdd(treeList, newData, uuid = true, childrenField = 'children') {
const addKey = (arr) => {
if (uuid) {
return arr?.map((item) => ({
uuid: createUuid(),
...item,
...newData,
[childrenField]: item[childrenField] ? addKey(item[childrenField]) : []
}))
}
return arr?.map((item) => ({
...item,
...newData,
[childrenField]: item[childrenField] ? addKey(item[childrenField]) : []
}))
}
const newTree = addKey(deepClone(treeList))
return newTree
}
export function addTreeChildren(val, tree, newData = {}, type = 'level', key = 'aid', first = false) {
const newTree = deepClone(tree)
let hasFound = false
const traversal = data => {
for (let i = 0; i < data.length; i++) {
if (hasFound) return
const info = data[i]
if (lodashGet(info, key) !== val && info.children) {
traversal(info.children)
} else if (lodashGet(info, key) === val) {
hasFound = true
const index = data.findIndex(item => val === lodashGet(item, key))
if (type === 'level') {
if (first) {
data.splice(index, 0, newData)
return
}
data.splice(index + 1, 0, newData)
} else {
const dealData = { ...data[index], children: [newData, ...data[index]?.children] }
data.splice(index, 1, dealData)
}
}
}
}
traversal(newTree)
return newTree
}
export function delTreeChildren(val, tree, key = 'aid') {
const newTree = deepClone(tree)
const traversal = data => {
for (let i = 0; i < data.length; i++) {
const info = data[i]
if (lodashGet(info, key) !== val && info.children) {
traversal(info.children)
} else if (lodashGet(info, key) === val) {
const index = data.findIndex(item => val === item[key])
data.splice(index, 1)
i--
}
}
}
traversal(newTree)
return newTree
}