当前位置:网站首页>处理树形结构数据
处理树形结构数据
2022-07-24 06:02:00 【MMNHD】
// 封装树形数据处理
// 核心思想: 寻找父节点的过程 通过pid去匹配id 如果匹配上了就把当前项push到匹配项的chilren属性中
// 固定的实现步骤:
// 1. 循环遍历数组 以数组中每一项的id做为key,每一项本身作为value 形成一个新的对象 [方便查找父节点]
// 2. 遍历数组 以数组中的每一项的pid去第一步形成的对象中匹配id 如果匹配的上 就代表是它的子节点
// push到chilren属性中 如果匹配不到 代表它自己就是最外层父节点 直接push到最终产出的树形数组中
/**
const map = {
'1': {
id:1,
pid:null
},
'2':{
id:2
pid:1
}
}
const arr = [
{
id:1,
pid:null
},
{
pid:1,
id:2
}
]
*/
function transTree(arr) {
const treeArr = []
// 逻辑处理
const map = {}
arr.forEach((item) => {
map[item.id] = item
map[item.id].children = []
})
arr.forEach(item => {
// 对象取值的技巧 如果pid作为key可以取到值 代表 匹配上了
if (map[item.pid]) {
map[item.pid].children.push(item)
} else {
treeArr.push(item)
}
})
return treeArr
}
export default transTree
// 有没有其他的办法
// 时间复杂度 o(n)
// 递归写法 函数自身调用 只要有函数调用 就会压栈操作 一旦超过最大的内存就会出现栈溢出
边栏推荐
- [media controller] open source project learning notes (based on Arduino micro development board)
- Breadth first search (template use)
- 不要太在意别人对你的看法
- PostgreSQL date handler usage
- Sealos 打包部署 KubeSphere 容器平台
- SparkSQL核心使用,220724,
- xavier_ normal_ Initialization test
- Don't compare with anyone, just be yourself
- 【学习笔记】Web页面渲染的流程
- You can't satisfy everyone!
猜你喜欢
![[lvgl (1)] a brief introduction to lvgl](/img/2e/2e155f1d3669c27ad1b090ca954224.png)
[lvgl (1)] a brief introduction to lvgl

Three level classification / menu query tree structure

Special effects - when the mouse moves, there will be a custom expression trail

《大厂面试》之JVM篇21问与答

Geek planet ByteDance one stop data governance solution and platform architecture
![[media controller] open source project learning notes (based on Arduino micro development board)](/img/08/39ed97437f235806c6d4415f53c47b.png)
[media controller] open source project learning notes (based on Arduino micro development board)

owasp top10 渗透测试

OSS authorizes a single bucket permission

Esp32 ultra detailed learning record: NTP synchronization time

创建WPF项目
随机推荐
华为专家自述:如何成为优秀的工程师
不运动也能增肌???打一针冬眠黑熊的血清就行
Kubernetes rapid installation
String question
Redis special data type Geo
自己的人生无须浪费在别人的标准中
xavier_normal_ 初始化测试
String问题
【学习笔记】Web页面渲染的流程
JSONObject按照key的A——Z顺序排序
[learning notes] Web page rendering process
[learning notes] possible reasons and optimization methods for white screen on Web pages
Kubernetes' deployment, service concept, dynamic capacity expansion
Don't care too much about what others think of you
Breadth first search (template use)
tensorflow scatter_nd函数
Record the pits encountered in the deserialization of phpserializer tool class
Redis数据类型-列表List
Sealos packages and deploys kubesphere container platform
Three level classification / menu query tree structure