Q:

Get the location of an object in an array with JS/jQuery

Let's assume I have an array as following:
[
    {
        "name": "list",
        "text": "SomeText1"
    },
    {
        "name": "complex",
        "text": "SomeText2",
        "config": {
            "name": "configItem",
            "text": "SomeText3",
            "anotherObject": {
                "name": "anotherObject1",
                "text": "SomeText4"
            }
        }
    }
]

I am using this awesome code to get all Objects with a certain key (http://techslides.com/how-to-parse-and-search-json-in-javascript). In my example it is getObjects(data,'text','') which will return all nodes as Object due to the appearance of text as key.
My only problem is, that I need to know the location of the returned Object in the whole array.
Is there any way to get it? Or at least the depth of the object in conjunction to the array?
getObjects(r,'text','')[0] (name = list) -> depth 1
getObjects(r,'text','')[1] (name = complex) -> depth 1
getObjects(r,'text','')[2] (name = configItem) -> depth 2

A:

You will need something along these lines:
function getObjectsDepth(obj, key, val, depth) {
    var objects = [];
    for (var i in obj) {
        if (!obj.hasOwnProperty(i)) continue;
        if (typeof obj[i] == 'object') {
            objects = objects.concat(getObjectsDepth(obj[i], key, val,++depth));    
        } else 
        //if key matches and value matches or if key matches and value is not passed (eliminating the case where key matches but passed value does not)
        if (i == key && obj[i] == val || i == key && val == '') { //
            objects.push(depth);
        } else if (obj[i] == val && key == ''){
            //only add if the object is not already in the array
            if (objects.lastIndexOf(obj) == -1){
                objects.push(depth);
            }
        }
    }
    return objects;
}

This will return the depth of the object, but not the object itself, just pass a 0 or 1 as last param, based on how you want to count.
If you want both the object and the depth at the same time you need to obj.push({'obj':obj,'depth':depth}).

