前言
使用范围:el-cascader级联选择器,父子不关联,返回数据是平级,需要回写
将平级数据处理成tree状的父子数据
/*
*将平级数据处理成父子关系的tree数据
*适用于根据parentId和id确认子父关系的平级数据
*parentId和id可自行替换成实际确认子父关系的属性
*参数list是平级数据
*/
//
ListToTree(list,parentId,id) {
const copyList = list.slice(0);
const tree = [];
for (let i = 0; i < copyList.length; i++) {
let if_father = true; //如果遍历后,copyList[i]没有父集,if_father为true,有父集为false
// 找出每一项的父节点,并将其作为父节点的children
for (let j = 0; j < copyList.length; j++) {
if (copyList[i].parentId === copyList[j].id) {
//如果copyList[i]有父集,if_father=false
if_father = false;
if (
copyList[j].children === undefined ||
copyList[j].children == ""
) {
copyList[j].children = [];
}
// 根据sn确定当前层级下标
copyList[j].children.push(copyList[i]);
// copyList[j].children[copyList[i].sn - 1] = copyList[i];
}
}
//如果该项没有父节点,则将其当根节点
if (if_father) {
tree.push(copyList[i]);
}
}
return tree;
},
将数据id,处理成级联选择器识别的数组id
/*
*递归补全数组回填级联
*参数id是你回填的id
*参数arr是你要循环的平级数组
*参数getIdArr是最终得到的多级id数组
*/
fn_cascader_recursion_id(id,arr,getIdArr){
for(const item of arr) {
if (item.id===id) {
getIdArr.unshift(id);
this.fn_cascader_recursion_id(item.parentId,arr,getIdArr);