Can this iterating javascript code be optimized? Say I have this type of code I'd like to execute. There's some data encapsulated around a big Javascript object containing methods &amp; properties that I'd like to extract based on comparing some other data in said object. The object includes associative (hash?) arrays where I don't know the array IDs at runtime so I have to do some iteration, this is the working code structure I came up with. But it's bloated and a bit messy to read. Was wondering it it can be optimized for efficiency and readability in general, to minimize iteration and conside the length of the object referencing.

I execute this code from Firebug console (or via Selenium WebDriver's execute javascript command, in which case console.log become "return" to return the desired value).

for(x in MainObj.aaa.bbb[MainObj.someGetIdMethod()].someObjArry){
    if (MainObj.aaa.bbb[MainObj.someGetIdMethod()].someObjArry[x].someObj.displayName == 'some value')
        console.log(MainObj.aaa.bbb[MainObj.someGetIdMethod()].someObjArry[x].someObj.someId);
}
You should cache all methods calls - JS is interpreting language and
there is no optimizers to help you, therefore, each time you call
method, get element from array etc, you are actually asking JS
engine to DO this for you.
Concluding that someObjArry is an array, should avoid using loops with "in" statements - use standard loops with indexes instead. "in" statement walks through all object's properties, not collection's elements, so it's just future maintenance "watch-out".
Property "displayName" of object "someObj" seems like of a string type - try using strong type comparisons if possible (not an optimization, just a good practice)
Cache as much as you can




var someArray = MainObj.aaa.bbb[MainObj.someGetIdMethod()].someObjArry, 
    arrayElement;

for(var i=0, $length = someArray.length; i&lt; $length; i++){
    arrayElement = someArray[i].someObj;

    if (arrayElement.displayName === 'some value'){
        console.log(arrayElement.someId);
    }
}