Javascript 递归获取嵌套对象中给定节点的完整路径(父层次结构)
我需要一个typescript函数,通过传递给定节点的值,递归地获取该节点的完整路径(父层次结构) 假设我有一个这样的对象数组:Javascript 递归获取嵌套对象中给定节点的完整路径(父层次结构),javascript,typescript,Javascript,Typescript,我需要一个typescript函数,通过传递给定节点的值,递归地获取该节点的完整路径(父层次结构) 假设我有一个这样的对象数组: items = [{ value: 2, text: "Name 2", children: [{ value: 7, text: "Name 7", children: [{ value: 10,
items = [{
value: 2,
text: "Name 2",
children: [{
value: 7,
text: "Name 7",
children: [{
value: 10,
text: "Name 10",
children: []
},
{
value: 11,
text: "Name 11",
children: []
},
{
value: 12,
text: "Name 12",
children: [{
value: 13,
text: "Name 13",
children: [{
value: 14,
text: "Name 14",
children: []
},
{
value: 15,
text: "Name 15",
children: []
}
]
}]
}
]
}]
},
{
value: 16,
text: "Name 16",
children: [{
value: 17,
text: "Name 17",
children: [{
value: 18,
text: "Name 18",
children: []
},
{
value: 19,
text: "Name 19",
children: []
}
]
}]
}
];
假设我想通过调用函数获得值为19的节点的完整路径
getPath(items, 19);
预期结果可能是仅返回父节点的值
[16, 17, 19]
或对象数组,如下所示:
[{
价值:16,
正文:“姓名16”
},
{
价值:17,
正文:“姓名17”
},
{
价值:19,
正文:“名称19”
}
]
谢谢,希望这有帮助
const items = [{
value: 2,
text: "Name 2",
children: [{
value: 7,
text: "Name 7",
children: [{
value: 10,
text: "Name 10",
children: []
},
{
value: 11,
text: "Name 11",
children: []
},
{
value: 12,
text: "Name 12",
children: [{
value: 13,
text: "Name 13",
children: [{
value: 14,
text: "Name 14",
children: []
},
{
value: 15,
text: "Name 15",
children: []
}
]
}]
}
]
}]
},
{
value: 16,
text: "Name 16",
children: [{
value: 17,
text: "Name 17",
children: [{
value: 18,
text: "Name 18",
children: []
},
{
value: 19,
text: "Name 19",
children: []
}
]
}]
}
];
function getPath(items, val) {
for (let i = 0; i < items.length; i++) {
const item = items[i];
if (item.value !== val) {
if (item.children) {
const path = getPath(item.children, val);
if (path) {
path.unshift(item.value);
return path;
}
}
} else {
return [item.value];
}
}
}
console.log(getPath(items, 19));
const项=[{
价值:2,
文字:“姓名2”,
儿童:[{
数值:7,
文本:“名称7”,
儿童:[{
数值:10,
正文:“名称10”,
儿童:[]
},
{
价值:11,
正文:“名称11”,
儿童:[]
},
{
数值:12,
文字:“姓名12”,
儿童:[{
价值:13,
正文:“姓名13”,
儿童:[{
价值:14,
正文:“姓名14”,
儿童:[]
},
{
价值:15,
正文:“姓名15”,
儿童:[]
}
]
}]
}
]
}]
},
{
价值:16,
正文:“姓名16”,
儿童:[{
价值:17,
正文:“姓名17”,
儿童:[{
价值:18,
文字:“姓名18”,
儿童:[]
},
{
价值:19,
正文:“姓名19”,
儿童:[]
}
]
}]
}
];
函数getPath(项目,val){
for(设i=0;i
下面是您的代码出了什么问题的答案如果您能分享您已有的代码并指出它不起作用的地方,这将非常有帮助。@NinaScholz没什么问题!我只需要一个函数如何得到一个给定节点的完整路径。