I am trying to search through an array of objects using Underscore.js, but I can't seem to target the one I want.
console.log(_.findWhere(response.data, { TaskCategory: { TaskCategoryId: $routeParams.TaskCategory } }));
However, this is returning undefined
$routeParams.TaskCategory
is equal to 301
This is an example of the objects inside the array I am searching. This data is represented by data.response
[{
"TaskCategory": {
"TaskCategoryId": 201,
"TaskName": "TaskName"
},
"TaskCount": 1,
"Tasks": [{
"EventTypeId": 201,
"EventName": "Event Driver",
"EventDate": "0001-01-01T00:00:00",
"EventId": "00000000-0000-0000-0000-000000000000",
}]
},
{
"TaskCategory": {
"TaskCategoryId": 301,
"TaskName": "TaskName"
},
"TaskCount": 1,
"Tasks": [{
"EventTypeId": 201,
"EventName": "Event Driver",
"EventDate": "0001-01-01T00:00:00",
"EventId": "00000000-0000-0000-0000-000000000000",
}]
}]
So I want the second object in that array using the TaskCategory.TaskCategoryId
, is it possible to get it using Underscore?
Use
_.find
instead of findWhere:They are similar, but
findWhere
is designed for special cases where you want to match key-value pairs (not useful in your scenario as it involves nested objects).Find
is more general-use, because it lets you provide a function as the predicate.The source of
_.findWhere
/_.where
is as followsAs you can see, it performs strict equality rather than deep equality. If you want a deep searching where, this would suffice (untested, unoptimized):
And you would be able to use your code, almost unchanged