Javascript 我如何访问我所知道的像树一样动态设置关键帧的对象

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 = {

我有下面这样的动态数据树结构,但数据是可变的(例如,可以将子元素添加到id:6)元素,我想访问它我知道id name节点,例如id是7我这样访问它

tree.children[0]。children[0]。children[1]

但是如果我只知道id名,如果我不知道它在哪个节点上,我怎么能从给定的树结构中找到它呢 为了更好地理解,例如,我只知道id是7,我想创建一个树。children[0]。children[0]。children[1]此路径如何动态执行

  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;ilog(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(节点)const[obj,path]=findById(7,tree,'tree'),那么就有了对象和字符串路径。如果要使用路径访问该项,可以执行
eval(path)
操作,它将获得该项。我希望访问id的7个元素路径,如tree.children[0]。children[0]。children[1]