Javascript 如何从树对象获取给定路径的子树?
我有一个树对象的形式:Javascript 如何从树对象获取给定路径的子树?,javascript,angularjs,Javascript,Angularjs,我有一个树对象的形式: var data = [{ "root": true, "label": null, "question": "What product category?", "nodes": [{ "label": "Clothes", "question": "What type of clothing?", "nodes": [{ "label": "Jeans",
var data = [{
"root": true,
"label": null,
"question": "What product category?",
"nodes": [{
"label": "Clothes",
"question": "What type of clothing?",
"nodes": [{
"label": "Jeans",
"question": "Color of jeans?",
"nodes": [{
"label": "Blue",
"question": null,
"nodes": null
},
]
}]
}]
}];
我试图返回给定路径为数组[0,0,0]的子树,该路径将返回
数据[0]。节点[0]。节点[0]
。我正在尝试一种迭代方法,是否可以用递归方法进行呢?下面是递归函数:
函数子树(arr,索引){
var a=arr[指数[0]];
返回index.length>1?子树(a.nodes,index.slice(1)):a;
}
风险值数据=[{
“根”:对,
“标签”:空,
“问题”:“什么产品类别?”,
“节点”:[{
“标签”:“衣服”,
“问题”:“什么类型的衣服?”,
“节点”:[{
“标签”:“牛仔裤”,
“问题”:“牛仔裤的颜色?”,
“节点”:[{
“标签”:“蓝色”,
“问题”:无效,
“节点”:空
}]
}]
}]
}];
log(子树(数据,[0,0,0])代码>
作为控制台包装{max height:100%!重要;top:0;}
什么是(0:0:0)?一根绳子?包括括号吗?请提供您尝试使用的代码。更新了问题,它最初是一个转换为数组的字符串。您似乎忘记了使用]
关闭所有嵌套数组。谢谢,这就是我的想法。我已经有一段时间没有写递归函数了:)。你能给我一些关于思维过程的见解吗?我在答案中添加了对我思维过程的描述;-)我很感激。非常感谢你。