我有一个JSON,如下所示
var json = {
"name": "Soft Drinks",
"T2": [
{
"name": "Bottled",
"T3": [
{
"name": "Apple",
"leaf": [
{
"name": "Apple 500 ML"
},
{
"name": "Apple 1 Ltr"
}
]
}
]
},
{
"name": "Fountain",
"T3": [
{
"name": "Apple",
"leaf": [
{
"name": "Apple Regular, 500 ML"
}
]
}
]
},
{
"name": "Tin",
"T3": [
{
"name": "Apple",
"leaf": [
{
"name": "Apple Regular, 300 ML"
}
]
}
]
}
]
}
我试图通过提供路径来搜索JSON
案例1:
例如,如果我提供路径为
var patharray = ["Soft Drinks","Bottled"] ; //(Bottled doesn't have leaf )
我需要的输出是Apple
案例2:
例如,如果我提供路径为
var patharray = ["Soft Drinks","Bottled","Apple"] ; //(Apple has got leaf )
我需要的输出是
"leaf": [
{
"name": "Apple 500 ML"
},
{
"name": "Apple 1 Ltr"
}
]
我尝试使用以下方法,但现在它无法正常工作。
function findElement(obj, patharray, index) {
var res = '';
if(index < patharray.length) {
var searchStr = patharray[index];
index++;
for(each in obj) {
if(obj[each] instanceof Array) {
var found = false;
for(var i=0;i<obj[each].length;i++) {
if(obj[each][i].name == searchStr) {
res = obj[each][i];
if(index<patharray.length) {
console.log('search again')
res = findElement(obj[each][i], patharray, index);
}
found = true
break;
}
}
if(found) {
break;
}
}
}
return res
}
}
var patharray = ["Ice creams","Stick","Frosty"] ;
console.log(findElement(json, patharray, 0));
答案 0 :(得分:1)