子节点查找所有父节点
// 子节点查找所有父节点
findPatentValue (array, targetId, valueKey, childrenKey) {
if (!targetId || !Array.isArray(array)) return [];
const result = [];
let valid = false;
const seek = (_array, _targetId) => {
let parentValue = '';
const up = (_array_, _targetId_, lastValue) => {
_array_.forEach((v) => {
const val = v[valueKey];
const child = v[childrenKey];
if (val === _targetId_) {
valid = true;
parentValue = lastValue;
return;
}
child?.length && up(child, _targetId_, val);
});
};
up(_array, _targetId);
if (parentValue) {
result.unshift(parentValue);
seek(_array, parentValue);
}
};
seek(array, targetId);
return valid ? [...result, targetId] : [];
},
树扁平化
treeToFlat (treeList, flatList) {
// flatList.length > 9999 是考虑底线保护原则,出于极限保护的目的设置的,可不设或按需设置。
if (flatList.length > 9999) {
return;
}
// eslint-disable-next-line array-callback-return
treeList.map((e) => {
e.value = e.label;
flatList.push(e);
// 递归:有条件的自己调用自己,条件是 e.children.length 为真
if (e.children && e.children.length) {
this.treeToFlat(e.children, flatList);
}
});
// console.log('扁平化后:', flatList)
return flatList;
},
给树添加深度属性
arrayTreeAddLevel (array, levelName = 'level', childrenName = 'children') {
if (!Array.isArray(array)) return []
const recursive = (array, level = 0) => {
level++
return array.map(v => {
v.visible = true
v[levelName] = level
const child = v[childrenName]
if (child && child.length) recursive(child, level)
return v
})
}
return recursive(array)
},
判断同级结点下是否有重复数据
judgeSameLabel(list) {
let flag = false
// 设立单独的标识用于中断递归函数
const recursion = list => {
if (flag) return false
for (let i = 0; i < list.length; i++) {
for (let j = i + 1; j < list.length; j++) {
if (list[i].label === list[j].label || list[i].value === list[j].value) {
flag = true
}
}
if (list[i].children && list[i].children.length !== 0) {
recursion(list[i].children)
}
}
}
recursion(list)
return flag
}
根据id查找树结构中的某一项
根据id查找树结构中的某一项
findItemById(list, id) {
let target = null
const recursion = list => {
if (target) return false
list.forEach(item => {
if (item.id === id) {
target = item
} else if (item.children && item.children.length !== 0) {
recursion(item.children)
}
})
}
recursion(list, id)
return target
}
级联数组删除空children数据
场景:element-ui 级联选择器的如果删除了子项导致子项为空数组,会出现子项选不中的情况
filterEmptyChildren(list) {
for (let i = 0; i < list.length; i++) {
const item = list[i]
if (item.children && item.children.length == 0) {
item.children = undefined
} else if (item.children && item.children.length !== 0) {
this.filterEmptyChildren(item.children)
}
}
}