How do I recursively search an object tree and return the matching object based on a key/value using JavaScript/Prototype 1.7

I went a slightly different route and made the findKey method an Object protype:

Object.prototype.findKey = function(keyObj) {
    var p, key, val, tRet;
    for (p in keyObj) {
        if (keyObj.hasOwnProperty(p)) {
            key = p;
            val = keyObj[p];
        }
    }

    for (p in this) {
        if (p == key) {
            if (this[p] == val) {
                return this;
            }
        } else if (this[p] instanceof Object) {
            if (this.hasOwnProperty(p)) {
                tRet = this[p].findKey(keyObj);
                if (tRet) { return tRet; }
            }
        }
    }

    return false;
};

Which you would call directly on the data object, passing in the key/value you're looking for:

data.findKey({ id: 3 });

Note that this function allows you to find an object based on any key:

data.findKey({ name: 'Template 0' });

See example → (open console to view result)


Not the best of the and final solution. But can get you a start for what you are looking...

var data = [{id: 0, name: 'Template 0', subComponents:[
        {id: 1, name: 'Template 1', subItems:[
            {id: 2, name: 'Template 2', subComponents:[{id: 3, name: 'Template 3'}], subItems: [{id: 4, name: 'Template 4'}]}
        ]}
    ]}
];


function returnObject(data,key,parent){
    for(var v in data){

        var d = data[v];
        if(d==key){
            return parent[0];
        }
        if(d instanceof Object){
            return returnObject(d,key,data);
        };

    }
}

function returnObjectWrapper(datavar,key){
    return returnObject(datavar,key.id)
}

returnObjectWrapper(data,{id:3})