I have a JSON as shown below
  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"
                            }
                        ]
                    }
                ]
            }
        ]
    }
I am trying to search the JSON by providing the path
Case 1 :
For example if i provided a path as
var patharray = ["Soft Drinks","Bottled"] ; //(Bottled doesn't have leaf )
The Output i needed is Apple
Case 2 :
For example if i provided a path as
var patharray = ["Soft Drinks","Bottled","Apple"] ; //(Apple has got leaf )
The Output i needed is
 "leaf": [
                            {
                                "name": "Apple 500 ML"
                            },
                            {
                                "name": "Apple 1 Ltr"
                            }
                        ]
I tried it using the following way , but right now its not working .
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));