Find a nested property in an object This works fine and returns an object from a nested "structure" by Id.

I would like to know if you could suggest a better approach, possible a faster one.

&lt;script&gt;
var data = {
    item: [
        {
            itemNested: [
                {
                    itemNested2: [{
                        id: "2"
                    }
                    ]
                }
            ]
        }
    ]
};

function findById(obj, id) {
    var result;
    for (var p in obj) {
        if (obj.id === id) {
            return obj;
        } else {
            if (typeof obj[p] === 'object') {
                result = findById(obj[p], id);
                if (result) {
                    return result;
                }
            }
        }
    }
    return result;
}


var result = findById(data, "2");
console.log(result);
&lt;/script&gt;
From a once over:


Be careful for js structure with cycles (like nodes in the DOM), you will get into an infinite loop.
This will also not find dupes, that may or may not be a problem
You also want to think about whether you want to prevent finding id in the inherited values with o.hasOwnProperty(p)
Dont check for if (obj.id === id) { in your loop, it's a waste of cycles. Check prior
Personally I tend to go either for the Spartan o or the full object, obj seems meh


I would use this version:

function findById(o, id) {
    //Early return
    if( o.id === id ){
      return o;
    }
    var result, p; 
    for (p in o) {
        if( o.hasOwnProperty(p) &amp;&amp; typeof o[p] === 'object' ) {
            result = findById(o[p], id);
            if(result){
                return result;
            }
        }
    }
    return result;
}