I have a json data with specific key as below:
var object = {"85":{"id":"50","nosurat":"2020-PKL-001","user_created":"02211"},"69":{"id":"50","nosurat":"2020-PKL-002","user_created":"02212"},"104":{"id":"50","nosurat":"2020-PKL-003","user_created":"02213"}};
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?
for(var keys in object){ if(object[keys].nosurat == "2020-PKL-001"){ functionx(); } }
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()
:
var obj = {"85":{"id":"50","nosurat":"2020-PKL-002","user_created":"02211"},"69":{"id":"50","nosurat":"2020-PKL-001","user_created":"02212"},"104":{"id":"50","nosurat":"2020-PKL-001","user_created":"02213"}}; function functionx(o){console.log(o)} console.log('=== correct behaviour ========================'); Object.values(obj).some(o=>o.nosurat=="2020-PKL-001" && functionx(o) || true); console.log('=== alternative correct version =============='); Object.values(obj).some(o=>o.nosurat=="2020-PKL-001" && (functionx(o),true) ); console.log('===== WRONG behaviour (previous version ======'); Object.values(obj).some(o=>o.nosurat=="2020-PKL-001" && functionx(o));
.as-console-wrapper {max-height:100% !important}
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.