請教各位前輩
今天想要在一個多層陣列物件中(有4層),每一層的架構都一樣
如果想要取得最子層的name = Apple是包含在那些子層的下面
不知道有沒有推薦的方法,目前是使用往回推的方式但效果並不佳
ps: id: 不重複
說明: 取Apple會得到資料如下
[{"id": 718,"name": "第一層"},{"id": 733,"name": "Layer2_1"},{"id": 734,"name": "L3_A"}]
{
"id": 718,
"name": "第一層",
"items": [
{
"id": 733,
"name": "Layer2_1",
"items": [
{
"id": 734,
"name": "L3_A",
"items": [
{
"id": 758,
"name": "Apple",
"items": null
},
{
"id": 760,
"name": "Banana",
"items": null
},
{
"id": 761,
"name": "Coco",
"items": null
}
]
},
{
"id": 764,
"name": "L3_AA",
"items": [
{
"id": 765,
"name": "Hamburger",
"items": null
}
]
}
]
},
{
"id": 759,
"name": "Layer2_2",
"items": [
{
"id": 762,
"name": "L3_B",
"items": [
{
"id": 763,
"name": "Dog",
"items": null
}
]
}
]
}
]
}
這是Json吧,
不是JQuery的問題...
練練手
依階層遞迴查找,id, name 可重複
支援搜尋所有name符合items(包含父階層)
function getPath( obj, KeyWord, FindAll ){
let Path_arr =[];
let path ={ id: obj.id, name: obj.name };
if( obj.name==KeyWord ){
Path_arr.push([ path ]);
}
if( obj.items!=null ){
$.each( obj.items, function(i, _obj ){
$.each( getPath( _obj, KeyWord, FindAll ), function(j, _path ){
_path.unshift( path );
Path_arr.push( _path );
});
if(!FindAll && Path_arr.length>0 ){ return false; }
});
}
return Path_arr;
}
var obj ={...ry};
var Path_arr = getPath( obj, 'Apple', false );
console.log( Path_arr );
Results: