views:

83

answers:

1

When building an ajax application, I normally prefer fetching remote data in JSON format. However, when the hierarchy is unpredictable (specifically geocoding responses from Google Maps API), it is tempting to go with XML format because the DOM method getElementsByTagName will get the data wherever it is in the hierarchy. Assuming there is only one element/property with the tag/name I'm interested in, is the following function an efficient equivalent to getElementsByTagName? How can it be improved?

function findProperty(obj,prop){

        for(var p in obj){
            if(p==prop){
                    return obj[p];
            }
            if(obj[p] instanceof Object){
                var tmp = findProperty(obj[p],prop);
                if(tmp){
                    return tmp;
                }
            }

        }
}
+2  A: 

Your function seems like a pretty straight forward linear search which many DOM traversal functions will do. That said, you should add a hasOwnProperty check to avoid getting properties from the prototype tree. e.g.

for(var p in obj) {
   if(obj.hasOwnProperty(p)) {
      ...
   }
}

Also, always use === instead of == in JS (this avoids, the rather bad, type coercion in JS). I'm also not sure that the instanceof statement does what you think it does. You'd probably want to use:

obj[o].constructor === Object

instead.

illvm
`instanceof` should be identical to `constructor` check here, although both will fail to "match" objects from other frames. It's also good to remember that `hasOwnProperty` is missing in some of the older clients, such as Safari <2.0.4.
kangax
instanceof *should* be the same, but as an example under FF 3.5 the following will return false:"as" instanceof Stringwhile this will return true:"as".constructor === String
illvm