当前位置:网站首页>Processing tree structured data
Processing tree structured data
2022-07-24 07:03:00 【MMNHD】
// Encapsulate tree data processing
// The core idea : The process of finding the parent node adopt pid To match id If it matches, put the current item push To match chilren Properties of the
// Fixed implementation steps :
// 1. Loop through groups In the form of id As key, Each item itself acts as value Form a new object [ It is convenient to find the parent node ]
// 2. Traversal array With each item in the array pid Go to match the object formed in the first step id If it matches It means its child nodes
// push To chilren Properties of the If it doesn't match Represents itself as the outermost parent node direct push To the tree array of the final output
/**
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 = []
// Logical processing
const map = {}
arr.forEach((item) => {
map[item.id] = item
map[item.id].children = []
})
arr.forEach(item => {
// Object value taking skills If pid As key You can get the value representative Match up
if (map[item.pid]) {
map[item.pid].children.push(item)
} else {
treeArr.push(item)
}
})
return treeArr
}
export default transTree
// Is there any other way
// Time complexity o(n)
// Recursive writing The function itself calls As long as there are function calls Stack pressing operation Once the maximum memory is exceeded, there will be stack overflow
边栏推荐
猜你喜欢
![[wechat applet] understand conditional rendering, list rendering and wxss template style](/img/97/cb78efcbcfe1a598da87751c482a98.png)
[wechat applet] understand conditional rendering, list rendering and wxss template style
![[lvgl (2)]](/img/f8/d04183cf74896295382765a9dfd88d.png)
[lvgl (2)]

Record the pits encountered in the deserialization of phpserializer tool class

tensorflow scatter_nd函数

一日一书:机器学习及实践——从零开始通往kaggle竞赛之路

一个AI玩41个游戏,谷歌最新多游戏决策Transformer综合表现分是DQN的两倍

STM32 MP3 music player based on FatFs r0.14b & SD card (also a simple application of FatFs)

Redis special data type hyperloglog

Sealos 打包部署 KubeSphere 容器平台

SPI——发送16位和8位数据
随机推荐
MapReduce(一)
Redis 持久化
【方向盘】IDEA的代码审查能力,来保证代码质量
tensorflow scatter_nd函数
2022-07-22 mysql/stonedb parallel hashjoin memory usage analysis
[waveform / signal generator] Based on stc1524k32s4 for C on Keil
Can you increase muscle without exercise??? Just get an injection of hibernating black bear serum
[learning notes] what happens when the URL is input into the page presentation?
Redis基本类型-有序集合Zset
反射
[jquery custom plug-in] 1 custom cache plug-in -jquerycache
Redis入门
mysql自动生成创建时间和更新时间
Redis 主从机制
Camera Hal OEM module ---- CMR_ grab.c
华为专家自述:如何成为优秀的工程师
Redis special data type hyperloglog
String question
Never lose yourself!
Gangster escape 3