当前位置:网站首页>Convert list data to tree data
Convert list data to tree data
2022-07-16 05:50:00 【Jason show】
problem
Sometimes the interface may give you list data , How to convert list data into tree data ???
such as :
Convert to :

Ideas :
- Recursive traversal found children, If pid Equal to the incoming id, Indicates that the current item is passed in id The child node of the corresponding item
- Closures save every traversal children
Realization
For a moment ts Detailed description of writing steps
const tranListToTreeData = <T, K>(list: T[], rootValue: string): K[] => {
// Store the data of child nodes
let arr: K[] = [];
// Traverse the list
list.forEach((item: {
[key: string]: any }) => {
// If the current item item Of pid be equal to roorValue, Describe current item item yes rootValue Child nodes of ( object type )
if (item.pid === rootValue) {
// Find the child node of the current item , without , Will return an empty array
const children = tranListToTreeData(list, item.id);
// If the array is not empty , It means that the current item has child nodes , And all child nodes are children in
if (children.length) {
// Mount all child nodes of the current item to the properties of the current item children Next
item.children = children;
}
// take rootValue All matching child nodes are placed in arr in
arr.push(item as K);
}
});
// Returns an array , Data of child nodes ( If the current item has no child nodes , Will return an empty array )
return arr;
};
If you need an adaptation ant-design-react Of Tree Components , Just be push Of item Switch to { key: item.id, title: item.name, children: item.children } that will do , Play by yourself .
边栏推荐
- 网页右边没有滚动条,内容超出也看不到怎么办?
- Intranet penetration notes - Sticky Keys and system command information collection
- [Huang ah code] Microsoft Internet Explorer will be retired. Netizens said: what should I do in the future?
- Single file component
- BUUCTF 神秘龙卷风
- 网络通信安全部分笔记——OSPF理论及实验
- [Huang ah code] Why do I suggest you choose go instead of PHP?
- Buuctf, let's sing a song
- 垃圾回收机制
- [ASIS 2019]Unicorn shop
猜你喜欢
随机推荐
[Huang ah code] getting started with MySQL - 2. Using data definition language (DDL) to operate the database
Basic knowledge of network
Svelte official introductory tutorial (1) - Introduction
2022第十五届全国大学生信息安全竞赛(ciscn)西南赛区部分WP
admin 系统被嵌套在第三方系统中的跨域异常
淘宝项目练习总结
window系统盘瘦身(开发)
内网渗透笔记——二层发现
[Huang ah code] you must learn these little knowledge points of MySQL for beginners
handsontable pro 授权码 key 生成器(JS函数)(仅供学习交流)
7.缓存击穿、缓存穿透、缓存
Free CDN jsdelivr acceleration website
7. Cache breakdown, cache penetration, cache
包管理工具
Component foundation of component-based programming
BUUCTF 后门查杀
JS收官笔记
自调用函数和因不声明变量而自动定义var的相关问题
Network security emergency response - basic skills
[yellow code] PHP saves remote resources locally


![[BJDCTF2020]Cookie is so stable](/img/d8/fb9fc2496ee8b23ec6fd6195051030.png)





![[安洵杯 2019]easy_web](/img/9d/f2c6fda2a96f4ac649dd553c9c2c55.png)
