/**
* 查找树的第一个叶子
* @param {*} tree 树
* @returns 第一个叶子
*/
export function firstNoChildrenNode(tree) {
for (const node of tree) {
if (!node.children) return node
if (node.children) {
const res = firstNoChildrenNode(node.children)
if (res) return res
}
}
return null
}
/**
* 将treenode结构拉平,成为一维数组
* @param {*} data 树数据
* @returns
*/
const flattenTreeData = data => {
const treeData = cloneDeep(data)
const flattenData = []
function flattenTree(tree, parentKey) {
tree.forEach(ele => {
const { children, key, ...other } = ele
flattenData.push({ ...other, key, parentKey })
if (children) {
flattenTree(children, key)
}
})
}
flattenTree(treeData, null)
return flattenData
}
/**
* 找到所有的父
* @param {*} key 节点唯一值
* @param {*} flattenTree 拉平的tree 数组
* @returns
*/
const findParent = (key, flattenTree) => {
const parentArr = [] // 存储所有的父级元素
function find(nodeId, tree) {
tree.forEach(ele => {
if (ele.key === nodeId) {
parentArr.unshift(ele)
find(ele.parentKey, tree)
}
})
}
find(key, flattenTree)
return parentArr
}
/**
* 找到当前节点
* @param {*} nodeId 要查找的节点ID
* @param {*} tree 树
* @param {*} treeKey 树的唯一键
* @returns 当前节点
*/
const findCurrentNode = (nodeId, tree, treeKey) => {
for (let index = 0; index < tree.length; index++) {
const element = tree[index]
if (nodeId === element[treeKey]) {
return element
}
if (element.children) {
const res = findCurrentNode(nodeId, element.children, treeKey)
if (res) {
return res
}
}
}
}
/**
* 模糊搜索
* @param {*} list 原数组
* @param {*} keyWord 查询关键字
* @param {*} attribute 检索数组的属性
* @returns 匹配到的数组
*/
export const fuzzyQuery = (list, keyWord, attribute = 'name') => {
const reg = new RegExp(keyWord)
const arr = []
for (let i = 0; i < list.length; i++) {
if (reg.test(list[i][attribute])) {
arr.push(list[i])
}
}
return arr
}
/**
* 获取父级key
* @param {*} tree 树
* @param {*} parentKey 父节点key值数组
* @returns 父节点key值数组
*/
export function getParentKey(tree, parentKey) {
for (let i = 0; i < tree.length; i++) {
if (tree[i].children) {
parentKey.push(tree[i].key)
getParentKey(tree[i].children, parentKey)
}
}
return parentKey
}
/**
* 获取所有的子,不包含父
* @param {*} parent 所有父节点key
* @param {*} key 要查找的key
* @returns 子key
*/
export function getChildKey(parent, keys) {
const arr = []
for (let i = 0; i < keys.length; i++) {
if (parent.indexOf(keys[i]) === -1) {
arr.push(keys[i])
}
}
return arr
}
03-27
1708