当前位置:网站首页>JS finds all the parent nodes or child nodes under a node according to the tree structure
JS finds all the parent nodes or child nodes under a node according to the tree structure
2022-07-03 02:46:00 【Brother Hua】
Let's take a look at the structure of the tree first :
[
{
"id":6,
"name":" test ",
"parent_id":1,
"children":[
{
"id":9,
"name":" test 1",
"parent_id":6,
"children":[
{
"id":20,
"name":" test 2",
"parent_id":9,
"children":[
{
"id":21,
"name":" test 3",
"parent_id":20,
},
{
"id":22,
"name":" test 4",
"parent_id":20,
},
{
"id":23,
"name":" test 5",
"parent_id":20,
}
],
}
],
},
]
Then it can be achieved by passing it back , There's no more nonsense , Go straight to the code :
// Find the parent node
parentTreeNode (treeList, id) {
var temp = []
var searchFn = function (treeList, id) {
for (var i = 0; i < treeList.length; i++) {
var item = treeList[i]
if (item.id === id) {
temp.push(item)
searchFn(treeList, item.parent_id)
break
} else {
if (item.children) {
searchFn(item.children, id)
}
}
}
}
searchFn(treeList, id)
return temp
}
// Find child nodes
childrenTreeNode (treeList, id) {
var temp = []
var searchFn = function (treeList, id) {
for (var i = 0; i < treeList.length; i++) {
var item = treeList[i]
if (item.parent_id === id) {
temp.push(item)
searchFn(treeList, item.id)
break
} else {
if (item.children) {
searchFn(item.children, id)
}
}
}
}
searchFn(treeList, id)
return temp
}
边栏推荐
猜你喜欢
【翻译】后台项目加入了CNCF孵化器
random shuffle注意
定了,就选它
Error when installing MySQL in Linux: starting mysql The server quit without updating PID file ([FAILED]al/mysql/data/l.pid
[principles of multithreading and high concurrency: 1_cpu multi-level cache model]
HW-初始准备
"Analysis of 43 cases of MATLAB neural network": Chapter 43 efficient programming skills of neural network -- Discussion Based on the characteristics of the new version of MATLAB r2012b
Classes and objects - initialization and cleanup of objects - constructor call rules
用docker 连接mysql的过程
搭建私有云盘 cloudreve
随机推荐
GBase 8c系统表pg_cast
Strategy application of Dameng database
GBase 8c 触发器(一)
Gbase 8C system table PG_ aggregate
Apple releases MacOS 11.6.4 update: mainly security fixes
Summary of interview project technology stack
二维格式数组格式索引下标连续问题导致 返回json 格式问题
Practice of traffic recording and playback in vivo
[shutter] banner carousel component (shutter_wiper plug-in | swiper component)
Packing and unpacking of JS
How to change the panet layer in yolov5 to bifpn
Oauth2.0 authentication, login and access "/oauth/token", how to get the value of request header authorization (basictoken)???
Sqlserver row to column pivot
Principle and application of database
Global and Chinese ammonium dimolybdate market in-depth analysis and prospect risk prediction report 2022 Edition
【翻译】Flux安全。通过模糊处理获得更多信心
搭建私有云盘 cloudreve
Why choose a frame? What frame to choose
Matlab tips (24) RBF, GRNN, PNN neural network
Source code analysis | resource loading resources