Underscore _.findWhere not finding element in array when it exists

4.2k views Asked by At

I'm trying to use the Underscore.js libarary's findWhere function to efficiently find an object from an array on a node.js server and I can't understand why it always returns undefined.

I tested the function using the node console and the object definetely contains an object with the specified key yet still nothing is returned when using findWhere.

Here I ensure that the value for the 'fixture' key I am looking for in findWhere does indeed equal the matching value in the object I was hoping to have returned:

'55785f4e38bd12511018145d' == predictions[0].fixture;

true

When checking what values were held in the array being searched by findWhere I confirm that the value does exist:

predictions

[ { fixture: '55785f4e38bd12511018145d' } ]

Checking the value I hope to have returned:

predictions[0].fixture

'55785f4e38bd12511018145d'

Running the findWhere query which returned undefined:

var foundPrediction = underscore.findWhere(predictions, {fixture: '55785f4e38bd12511018145d'});

undefined

The only reasons I can think of are that this has something perhaps to do with casting or maybe a '===' that returns false within the function, but is there any way I can get findWhere to return the object as desired, or will I have to resort to a manual search using a for loop?

Thanks in advance!

1

There are 1 answers

0
Gopinath Shiva On BEST ANSWER

There is nothing wrong in your code. Looks like you're running in console, thats why after hitting enter , console is showing undefined. You perhaps thought that foundPrediction value is undefined. You need to console the foundPrediction variable to get the required result.

Also there is nothing wrong with casting as it returns true.

var predictions = [{
    fixture:'55785f4e38bd12511018145d'
}]
console.log('55785f4e38bd12511018145d' === predictions[0].fixture);
var foundPrediction = _.findWhere(predictions, {fixture: '55785f4e38bd12511018145d'});
console.log(foundPrediction);

I have added the code in jsFiddle. Hope it helps