将平级数据转换成树状结构数据

每天学习一个小知识(第三天):

        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
  };

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值