JS 将扁平化数组转化为树形结构
程序员文章站
2022-04-24 21:56:14
...
后台返回数据如下:
{ 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 }
先要将数据格式转化为:
代码如下:
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) {
let cloneData = JSON.parse(JSON.stringify(data))
return cloneData.filter(parent => { //AREA_CODE 代表id PID代表 父级 pid
let branchArr = cloneData.filter(child => parent['AREA_CODE'] == child['PID']);
branchArr.length > 0 ? parent['children'] = branchArr : '';
return parent['PID'] == 0;
})
}
treeData(list1)
上一篇: 浮动练习与清除浮动
下一篇: 538. Convert BST to Greater Tree && 1038. Binary Search Tree to Greater Sum Tree
推荐阅读