I have following code:
$.each(data, function (key, val) {
var items = val.items;
console.log(val.id);
if (val.id === this.id) {
console.log('hello');
}
});
In the above code, I am looping through data which is a JSON object. Then I compare the id of val with this.id which has value of 4. Thus what I want is when val.id (4) equals to this.id (4) then log hello, however, since data has several objects so it logs several hellos.
Why and how can I make it so that it says hello only when it matches that condition and get out of that loop?
In the function defined within the call to
each(), this === val.If you’re trying to compare to the value of
this.idfrom before the call to each, you’ll need to cache it, like so: