首页 > 解决方案 > JavaScript-如何在数组中递归查找元素并返回其路径?

问题描述

数据结构看起来像这样

[{id: 1,
  items:[{ id: 2,
            items: [ id: 3]
           },

          { id: 4,
           items:[id: 5]
          }]
},
{
id: 6,
items:[{ id: 7,
         items: [ id: 8]
       },

       {id: 9,
        items:[id: 10]
       }]
}]

我想通过它找到一个元素id,并返回它的路径,包括它的父母的路径

例如,如果id=10,则 10 的路径是6.9.10

findId(array, id, path,pathList){

        array.map(i => {

            if(i.items == undefined){
                return;
            }


            path = path + '.' +item.id;
            pathList.push(path);

            if(i.id == id){
                return pathList;
            }else{
                pathList.pop();
                this.findId(i.fields, id, path, pathList);

            }
        })

    }

我的问题是,如何找到id=10并返回一个包含[6, 6.9, 6.9.10]

提前致谢!

标签: javascriptarrays

解决方案


你可以按照我的方法:

var obj = [{id: 1,
  items:[{ id: 2,
            items: [{id: 3}]
           },

          { id: 4,
           items:[{id: 5}]
          }]
},
{
id: 6,
items:[{ id: 7,
         items: [{id: 8}]
       },

       {id: 9,
        items:[{id: 10}]
       }]
}];
function searchId(object, index_to_find){
  //first, add depth (of each element) to array items
  var depths = object;
  //structure of path = [[0,length_1st],[1,length_2nd],[2,length_3rd],[3,length_4th],...,[last,length_last]]
  var path = [];
  //for first value of path
  path.push([0,depths.length]);
  //test to add depth for depths:
  depths.map(function add_depth(current){
    current['depth'] = path[path.length-1][0];
    if(current.items){
      //continue to array items
      path.push([path[path.length-1][0]+1,current.items.length]);
      current.items.map(add_depth);
    }else{
      //get back of path
      while(path.length>1 && path[path.length-1][1]<2){
          path.pop();
      }
      //decrease length path[...[x,length]]
      path[path.length-1][1]--;
    };
  });
  //console.log(depths);
  var path_result = [];
  var flagFound = false;
  depths.findIndex(function find_id(current,index){
      if (flagFound){
          return;
      };
      if(current.id===index_to_find){
          //finish at here
          path_result[current.depth] = index;
          flagFound = true;
          return;
      }else{
          if(current.items){
              path_result[current.depth] = index;
              current.items.findIndex(find_id);
          };
      };
  });
  if(!flagFound)
    return undefined;
  //console.log(path_result);
  var self_items;
  var path_end = "";
  var result_end = [];
  if(path_result){
    for(i=0;i<path_result.length;i++){
      if(i==0){
        let temp_id = object[path_result[i]].id;
        path_end = path_end + temp_id;
        result_end.push(path_end);
        self_items = object[path_result[i]].items;
      }else if(i==path_result.length-1){
        let temp_id = self_items[path_result[i]].id;
        path_end = path_end + "." + temp_id;
        result_end.push(path_end);
      }else{
        let temp_id = self_items[path_result[i]].id;
        path_end = path_end + "." + temp_id;
        result_end.push(path_end);
        self_items = self_items[path_result[i]].items;
      };
    }
  };
  //console.log(path_end);
  return result_end;
};
console.log(searchId(obj,10));
console.log(searchId(obj,8));


推荐阅读