const tree = {
id:"root",
children:[
{id:1,children:["id1"]},
{id:2,children:["id2"]},
{id:3,children:["id3"]},
{id:4,children:[
{id:5,children:["id4id5"]}
]},
{id:6,children:[
{id:7,children:[
{id:8,children:["id4id5"]}
]}
]}
]
}
function search(id,arr){
let asd = {};
arr.forEach((val,ind,arr)=>{
if(!val.id) {asd = "meiyou";return}
if(val.id == id){
asd["id"] = val.id;
asd["children"] = val.children;
console.log(asd); //
return;
}else{
search(id,val.children);
}
});
return asd;
}
var result = search(5,tree.children);
console.log(result); // {}
The first layer of the array can return normally, and if it is deeper, it will return {} and ask for the correct answer
.