{"id": 1,
"pid": 0,
"code": "310000",
"name": "浙江省",
"type": 0,
"memo": "",
"info": {},
"children": [
{
"id": 177,
"pid": 1,
"code": "",
"name": "温州市",
"type": 0,
"memo": "",
"info": {},
"children": []
},
{
"id": 3,
"pid": 1,
"code": "310000",
"name": "杭州市",
"type": 0,
"memo": "",
"info": {},
"children": [{
"id": 179,
"pid": 3,
"code": "",
"name": "西湖区",
"type": 0,
"memo": "",
"info": {},
"children": [
{"id": 179,
"pid": 179,
"code": "",
"name": "文一路",
"type": 0,
"memo": "",
"info": {},
"children": []}
]
}]
},{
"id": 11,
"pid": 1,
"code": "",
"name": "宁波市",
"type": 0,
"memo": "",
"info": {},
"children": []
}
]
}
这是json格式的树结构,比如:我想要取得id为179下面的children,采用递归怎么写啊。用js写一下,java也行。
"pid": 0,
"code": "310000",
"name": "浙江省",
"type": 0,
"memo": "",
"info": {},
"children": [
{
"id": 177,
"pid": 1,
"code": "",
"name": "温州市",
"type": 0,
"memo": "",
"info": {},
"children": []
},
{
"id": 3,
"pid": 1,
"code": "310000",
"name": "杭州市",
"type": 0,
"memo": "",
"info": {},
"children": [{
"id": 179,
"pid": 3,
"code": "",
"name": "西湖区",
"type": 0,
"memo": "",
"info": {},
"children": [
{"id": 179,
"pid": 179,
"code": "",
"name": "文一路",
"type": 0,
"memo": "",
"info": {},
"children": []}
]
}]
},{
"id": 11,
"pid": 1,
"code": "",
"name": "宁波市",
"type": 0,
"memo": "",
"info": {},
"children": []
}
]
}
这是json格式的树结构,比如:我想要取得id为179下面的children,采用递归怎么写啊。用js写一下,java也行。
<html><head>
<meta charset="utf-8">
<title></title>
</head><body>
<script>
var json = {
"id": 1,
"pid": 0,
"code": "310000",
"name": "浙江省",
"type": 0,
"memo": "",
"info": {},
"children": [{
"id": 177,
"pid": 1,
"code": "",
"name": "温州市",
"type": 0,
"memo": "",
"info": {},
"children": []
},
{
"id": 3,
"pid": 1,
"code": "310000",
"name": "杭州市",
"type": 0,
"memo": "",
"info": {},
"children": [{
"id": 179,
"pid": 3,
"code": "",
"name": "西湖区",
"type": 0,
"memo": "",
"info": {},
"children": [{
"id": 180,
"pid": 179,
"code": "",
"name": "文一路",
"type": 0,
"memo": "",
"info": {},
"children": []
}]
}]
}, {
"id": 11,
"pid": 1,
"code": "",
"name": "宁波市",
"type": 0,
"memo": "",
"info": {},
"children": []
}
]
}; function treeWalk(node, targetId) {
if (!node) {
return;
} // 找到结果,结束递归
if (node.id == targetId) {
window.foundChildren = node.children;
return;
} // 按 children 顺序深度优先递归遍历树
var children = node.children;
children.forEach((n) => {
treeWalk(n, targetId);
});
} treeWalk(json, 179);
console.log(JSON.stringify(window.foundChildren));
</script>
</body></html>
children.forEach((n) => {
treeWalk(n, targetId);
}); 这个=>是啥意思?
你自己改成循环children数组,将其中元素作为参数递归调用treeWalk方法即可