Javascript 我如何访问我所知道的像树一样动态设置关键帧的对象
我有下面这样的动态数据树结构,但数据是可变的(例如,可以将子元素添加到id:6)元素,我想访问它我知道id name节点,例如id是7我这样访问它 tree.children[0]。children[0]。children[1] 但是如果我只知道id名,如果我不知道它在哪个节点上,我怎么能从给定的树结构中找到它呢 为了更好地理解,例如,我只知道id是7,我想创建一个树。children[0]。children[0]。children[1]此路径如何动态执行Javascript 我如何访问我所知道的像树一样动态设置关键帧的对象,javascript,reactjs,algorithm,sorting,tree,Javascript,Reactjs,Algorithm,Sorting,Tree,我有下面这样的动态数据树结构,但数据是可变的(例如,可以将子元素添加到id:6)元素,我想访问它我知道id name节点,例如id是7我这样访问它 tree.children[0]。children[0]。children[1] 但是如果我只知道id名,如果我不知道它在哪个节点上,我怎么能从给定的树结构中找到它呢 为了更好地理解,例如,我只知道id是7,我想创建一个树。children[0]。children[0]。children[1]此路径如何动态执行 let tree = {
let tree = {
id: 1,
name: "tree1",
children: [
{
id: 2,
name: "tree2",
children: [
{
id: 4,
name: "tree4",
children: [
{
id: 6,
name: "tree6"
},
{
id: 7,
name: "tree7"
}
]
},
{
id: 5,
name: "tree5"
}
]
},
{
id: 3,
name: "tree3"
}
]
};
要访问它,请使用
document.getElementById(“tree7”、“tree6”)
。然后添加一些可执行的内容。或者使用一个变量
var tree6=document.getElementById(“tree6”);
var tree7=document.getElementById(“tree7”);
变量treesomething=tree6+tree7;
类似这样的内容:
让树={
id:1,
名称:“树1”,
儿童:[
{
id:2,
名称:“树2”,
儿童:[
{
id:4,
名称:“tree4”,
儿童:[
{
id:6,
名称:“tree6”
},
{
id:7,
名称:“树7”
}
]
},
{
id:5,
名称:“树5”
}
]
},
{
id:3,
名称:“tree3”
}
]
};
const findById=(id,obj,path='tree')=>{
if(obj.id==id)返回[obj,path];
else if(对象儿童){
for(设i=0;i log(findById(7,tree,'tree')代码>这就是你要找的吗
让树={
id:1,
名称:“树1”,
儿童:[{
id:2,
名称:“树2”,
儿童:[{
id:4,
名称:“tree4”,
儿童:[{
id:6,
名称:“tree6”
},
{
id:7,
名称:“树7”
}
]
},
{
id:5,
名称:“树5”
}
]
},
{
id:3,
名称:“tree3”
}
]
};
常量findNodeById=(节点,id)=>{
如果(node.id==id){
返回节点
}else if(node.children&&node.children.length>0){
for(让node.children的子级){
node=findNodeById(子节点,id);
如果(节点)
返回节点
}
}否则{
返回null;
}
}
const node=findNodeById(树,7);
console.log(节点)问题并不是说这棵树是DOM元素树。此解决方案假设我认为不准确。这次请不要删除您的问题。我正在制定解决方案,无法提交,因为您删除了以前的问题:)这是否回答了您的问题?我想访问id的7个元素路径,比如tree.children[0]。children[0]。children[1]是的,路径是正确的,但是让path=findById(7,tree,'tree'),那么路径[2]是字符串,而不是给这个{id:7,name:“tree7”},我怎么做呢?我不知道你的意思。如果您执行const[obj,path]=findById(7,tree,'tree')代码>,那么就有了对象和字符串路径。如果要使用路径访问该项,可以执行eval(path)
操作,它将获得该项。我希望访问id的7个元素路径,如tree.children[0]。children[0]。children[1]