Skip to content
Advertisement

Conditional statement inside for(var key in object) Javascript

I have a json data with specific key as below:

JavaScript

So, in order to iterate it, I use for method. The problem is how to make filters inside the for method, but only execute it once?

JavaScript

In the above code, the functionx() executed 3 times, because once it’s true, it will loop through as many key as my object has. How to make functionx() only executed once in a while, only when the condition is met, assuming that there will be another key that met the condition.

Advertisement

Answer

or you could use Array.prototype.some():

JavaScript
JavaScript

Edit:
Oooops, I just corrected a tiny detail: I forgot to mention that in my original solution functionx(o) needed to return some “truthy” value, otherwise multiple calls would still have happened in some()!

I changed the relevant part of the code now to (functionx(o) || true). This will make sure that some() will definitely stop after the first functionx() call (regardless of whatever functionx might return).

One further remark on the && within the function of the .some() loop: the evaluation of boolean expressions follows strict “lazy” rules in JavaScript (as in almost every other language): terms are evaluated from left to right only as far as necessary to get the result of the whole expression. So if the term before the && evaluates as false the overall result of the expression is determined and nothing after the && could change it anymore. Therefore functionx will not be called in these situations and false will be returned to the calling .some() loop.

Advertisement