Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
175 views
in Technique[技术] by (71.8m points)

javascript - Get an object from array which contains a specific value

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use _.find instead of findWhere:

console.log(_.find(response.data, function(item) {
    return item.TaskCategory.TaskCategoryId == $routeParams.TaskCategory; 
}));

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...