技术学习

我所喜欢的

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

1-因为树形结构在后台关系型数据库中一般是以表格的形式存在的,而对于UI层展示一般数据要求是树形结构的,特封装转换方法

   (1)列表转树形结构:

       

var list1 = [
				{AREA_NAME: "浙江省", level: 0,	PID: 0,AREA_CODE: 330000},
				{AREA_NAME: "杭州市",level: 1,PID: 330000,AREA_CODE: 330100},
				{AREA_NAME: "宁波市",level: 1,PID: 330000,AREA_CODE: 330200},
				{AREA_NAME: "温州市",level: 1,PID: 330000,AREA_CODE: 330300},
				{AREA_NAME: "嘉兴市",level: 1,PID: 330000,AREA_CODE: 330400},
				{AREA_NAME: "湖州市",level: 1,PID: 330000,AREA_CODE: 330500},
				{AREA_NAME: "上城区",level: 2,PID: 330100,AREA_CODE: 330102},
				{AREA_NAME: "下城区",level: 2,PID: 330100,AREA_CODE: 330103},
				{AREA_NAME: "江干区",level: 2,PID: 330100,AREA_CODE: 330104},
				{AREA_NAME: "河南省",level: 0,PID: 0,AREA_CODE: 410000},
				{AREA_NAME: "郑州市",level: 1,PID: 410000,AREA_CODE: 410100},
				{AREA_NAME: "开封市",level: 1,PID: 410000,AREA_CODE: 410200}
			]

			function treeData(data,option = { idField:'AREA_CODE',pidField:'PID',childrenKey:'children' }) {
				let cloneData = JSON.parse(JSON.stringify(data))
				return cloneData.filter(parent => { //AREA_CODE 代表id   PID代表 父级 pid
					let branchArr = cloneData.filter(child => parent[option.idField] == child[option.pidField])
					branchArr.length > 0 ? parent[option.childrenKey] = branchArr : ''
					return parent[option.pidField] == 0
				})
			}
			console.log(treeData(list1))

  效果如下:

 

posted on 2021-04-30 09:39  飘扬De黑夜  阅读(430)  评论(0编辑  收藏  举报