vignesh vignesh - 4 months ago 15x
jQuery Question

_.findWhere from underscorejs to JQuery

I am trying to implement this code: in my project.

Everything is fine except for the line:

t = _.findWhere(sc, { id : Number(a.trim()) });

They have used underscorejs and I want to translate this to JQuery without using another lib.

I went through the doc and it stated:

findWhere_.findWhere(list, properties)

Looks through the list and returns the first value that matches all of the key-value pairs listed in properties.

If no match is found, or if list is empty, undefined will be returned.

But still I am confused about this since I am not sure what to return exactly (as first value). Can anyone give me a JQuery alternative to that line?

Thanks in advance..


If you don't the generic nature of _.findWhere() you can use a simple while loop, and compare the id to the numeric value of a (fiddle):

t = 0; // t is used as a counter
aValue = Number(a.trim()); // assign the value to a variable instead of iterating it
while (t < sc.length && sc[t].id !== aValue) { t++; }; // find the index where the id is the as the aValue

t < sc.length && toSet.push(sc[t]); // if t is less the sc.length we found the item in the array

If you need a findWhere without underscore try this gist.