後臺返回給前端數據:前端
[{
"id": "1", //惟一標識id
"name": "女裝/男裝/內衣",
"parentId": "0" //父級id
}, {
"id": "2",
"name": "女裝",
"parentId": "1"
}, {
"id": "3",
"name": "男裝",
"parentId": "1"
}, {
"id": "4",
"name": "童裝",
"parentId": "1"
}, {
"id": "5",
"name": "內衣",
"parentId": "1"
}, {
"id": "6",
"name": "連衣裙",
"parentId": "2"
}, {
"id": "7",
"name": "毛呢外套",
"parentId": "2"
}, {
"id": "8",
"name": "休閒褲",
"parentId": "2"
}, {
"id": "9",
"name": "牛仔外套",
"parentId": "2"
}, {
"id": "10",
"name": "鞋靴/箱包/配件",
"parentId": "0"
}]it
前端處理數據io
let data1 = res.data;//後臺初始數據
function setTreeData(arr) {
// 刪除全部的children,以防止屢次調用
arr.forEach(function(item) {
delete item.children;
});
let map = {}; //構建map
arr.forEach(i => {
map[i.id] = i; //構建以id爲鍵 當前數據爲值
});
let treeData = [];
arr.forEach(child => {
const mapItem = map[child.parentId]; //判斷當前數據的parentId是否存在map中
if (mapItem) {
//存在則表示當前數據不是最頂層的數據
//注意: 這裏的map中的數據是引用了arr的它的指向仍是arr,當mapItem改變時arr也會改變,踩坑點
(mapItem.children || (mapItem.children = [])).push(child); //這裏判斷mapItem中是否存在child
} else {
//不存在則是頂層數據
treeData.push(child);
}
});
return treeData;
}
console.log(setTreeData(data1))console
處理結果:function
[{
"id": "1",
"name": "女裝/男裝/內衣",
"parentId": "0",
"children": [{
"id": "2",
"name": "女裝",
"parentId": "1",
"children": [{
"id": "6",
"name": "連衣裙",
"parentId": "2"
}, {
"id": "7",
"name": "毛呢外套",
"parentId": "2"
}, {
"id": "8",
"name": "休閒褲",
"parentId": "2"
}, {
"id": "9",
"name": "牛仔外套",
"parentId": "2"
}]
}, {
"id": "3",
"name": "男裝",
"parentId": "1"
}, {
"id": "4",
"name": "童裝",
"parentId": "1"
}, {
"id": "5",
"name": "內衣",
"parentId": "1"
}]
}, {
"id": "10",
"name": "鞋靴/箱包/配件",
"parentId": "0"
}]
後臺