Interview question: Write a find method to find any item in the data tree according to the id. (Ali front-end interview questions)

Ali front-end interview original question
Such as the title: Write a find method to find any item in the data tree according to the id.

const data = [{
    
    
  id:"1000",
  name:"深圳",
  children:[{
    
    
    id:"1001",
    name:"宝安区",
    children:[]
  },{
    
    
    id:"1002",
    name:"南山",
    children:[{
    
    
      id:"1012",
      name:"粤海街道",
      children:[{
    
    
        id:"1112",
        name:"阿里中心",
        children:[]
      },{
    
    
        id:"1212",
        name:"深圳湾人才公园",
        children:[]
      }]
    }]
  }]
},{
    
    
  id:"2000",
  name:"广州",
  children:[{
    
    
    id:"2001",
    name:"越秀区",
    children:[{
    
    
      id:"2011",
      name:"人民公园"
    }]
  },{
    
    
    id:"2002",
    name:"天河区",
    children:[]
  }]
}];
function find(data, id){
    
    
  for(let i=0; i<data.length; i++){
    
    
    if(data[i].id === id){
    
    
      // 找到匹配的id,返回对应的name
      return data[i].name;
    }
    if(data[i].children && data[i].children.length > 0){
    
    
      // 递归查找子节点
      const result = find(data[i].children, id);
      if(result && result !== "未找到"){
    
    
        // 如果找到了结果,并且不是"未找到",则返回结果
        return result;
      }
    }
  }
  // 遍历完整个data数组,仍未找到匹配的id,返回"未找到"
  return "未找到";
}
console.log(find(data, "1000"));   // 深圳
console.log(find(data, "2001"));   // 越秀区
console.log(find(data, "2011"));   // 人民公园
console.log(find(data, "1012"));   // 粤海街道
console.log(find(data, "1112"));   // 阿里中心
console.log(find(data, "1222"));   // 未找到

Guess you like

Origin blog.csdn.net/weixin_41636483/article/details/131447441