zoukankan      html  css  js  c++  java
  • javascript 扁平数组和树形结构转换

    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))
    

      效果如下:

  • 相关阅读:
    集群临时重启
    elasticsearch索引目录设置
    elasticsearch索引路径规则
    spring boot 使用application.properties 进行外部配置
    ELASTICSEARCH健康red的解决
    Elasticsearch——使用_cat查看Elasticsearch状态
    vmstat命令
    ava Maven项目之Nexus私服搭建和版本管理应用
    android 2.2 videoView 诡异bug
    华为部分设备运行很卡的问题
  • 原文地址:https://www.cnblogs.com/volts0302/p/14720838.html
Copyright © 2011-2022 走看看