每天学习一个小知识(第三天):
ps:同事写的一个处理树数据的公共方法,拿出来学习分享一下。
/**
* 将平级数据转换成树状结构数据
* @param {*} data
* @param {*} 禁用状态对象例如{type:'6'}
* @param {*}attributes 数组例如[value ,label] 或者undefined
* @returns getTreeList(res,[id,name],{})
* getTreeList(res)正常的树,有默认以id为value,以name为lable
* getTreeList(res,[value,lable])正常的树有以value为value,lable为lable
* getTreeList(res,underfund)正常的树有默认以id为value,以name为lable
* getTreeList(res,underfund,{type:6})正常的树有默认以id为value,以name为lable,只能选中type为6的可选其他的禁用
* getTreeList(res,underfund,undefined,{id:'132456'})正常的树有默认以id为value,以name为lable。禁用掉id为132456的数据。
*
*/
export const getTreeList = (data,attributes=['id','name'],disabled,unDisabled) => {
console.log(unDisabled)
// debugger
const resData = data;
const tree = [];
resData.map(element=>{
if (element.pId=='0') {
for (const key in disabled) {
if (element[key] != disabled[key]) {
element.disabled=true;
}
}
for(const k in unDisabled) {
if (element[k] == unDisabled[k]) {
element.disabled=true;
}
}
const parent = {
...element,
value:element[attributes[0]],
label:element[attributes[1]],
};
parent.children = getChild(element.id, resData) // 获取子节点
tree.push(parent)
}
})
function getChild(id,array) {
const child = []
for (const arr of array) { // 循环获取子节点
if (arr.pId == id) {
for (const key in disabled) {
if (arr[key] != disabled[key]) {
arr.disabled=true;
}
}
for(const k in unDisabled) {
if (arr[k] == unDisabled[k]) {
arr.disabled = true;
}
}
child.push({
...arr,
value:arr[attributes[0]],
label:arr[attributes[1]],
})
}
}
for (const item of child) { // 获取子节点的子节点
const childCopy = getChild(item.id, array)// 递归获取子节点
if (childCopy.length > 0) {
item.children = childCopy
}
}
return child
}
return tree
};