[英]JavaScript- How to find an element and return its path in an array recursively?
数据结构看起来像这样
[{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
,则id=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]
的数组
提前致谢!
你可以按照我的方法:
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));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.