Working on a js app involving many objects, I want to be able to grab an object by a specific variable. Here is my code:
var pin = '0000';
$.each(employees, function(){
if(this.pin === pin){
curEmployee = this;
return false;
}
});
Though this approach works, I have a feeling that there are way better solutions out there… I was fiddling around with grep and tried:
var pin = '0000';
curEmployee = $.grep(employees, function(e,i){
return e[pin] === pin;
});
However, it is harder to determine a result, since now I will need to check the length to see if an array with provided back, and such.
Just looking for a best practices solution.
Since an Array is always returned from
$.grep, just get the[0]index of the Array. Ifundefined, there was no match.Without jQuery, you could use
Array.prototype.filterin the same manner: