在项目开发中往往需要用到树形结构,可是后端返回的数据不符合树形结构,这时就需要我们自行转换成树状结构
- const convertToTree = (data:any) => {
- const map:any = {};
- const roots:any = [];
-
- data.forEach((item:any) => {
- map[item.id] = { ...item, children: [] };
- });
-
- data.forEach((item:any) => {
- if (item.parentId && map[item.parentId]) {
- map[item.parentId].children.push(map[item.id]);
- } else {
- roots.push(map[item.id]);
- }
- });
-
- return roots;
- }
convertToTree(res.data) //调用即可