后台返回给前端数据:
[{
"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"
}]
前端处理数据
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))
处理结果:
[{
"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"
}]