【发布时间】:2019-02-03 14:11:03
【问题描述】:
我试图弄清楚如何递归地在这个 JSON 对象中搜索一个节点。我尝试了一些东西但无法得到它:
var tree = {
"id": 1,
"label": "A",
"child": [
{
"id": 2,
"label": "B",
"child": [
{
"id": 5,
"label": "E",
"child": []
},
{
"id": 6,
"label": "F",
"child": []
},
{
"id": 7,
"label": "G",
"child": []
}
]
},
{
"id": 3,
"label": "C",
"child": []
},
{
"id": 4,
"label": "D",
"child": [
{
"id": 8,
"label": "H",
"child": []
},
{
"id": 9,
"label": "I",
"child": []
}
]
}
]
};
这是我的非工作解决方案,这可能是因为第一个节点只是一个值,而孩子们在数组中:
function scan(id, tree) {
if(tree.id == id) {
return tree.label;
}
if(tree.child == 0) {
return
}
return scan(tree.child);
};
【问题讨论】:
标签: javascript json recursion tree