从包含特定值的数组中获取对象 [英] Get an object from array which contains a specific value

查看:174
本文介绍了从包含特定值的数组中获取对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Underscore.js搜索一系列对象,但我似乎无法定位我想要的对象。

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 } }));

然而,这是返回 undefined
$ routeParams.TaskCategory 等于 301

However, this is returning undefined $routeParams.TaskCategory is equal to 301

这是我正在搜索的数组中的对象的示例。此数据由 data.response

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",
    }]
}]

所以我想要第二个对象该数组使用 TaskCategory.TaskCategoryId ,是否可以使用Underscore获取它?

So I want the second object in that array using the TaskCategory.TaskCategoryId, is it possible to get it using Underscore?

推荐答案

使用 _。find 而不是findWhere:

Use _.find instead of findWhere:

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

它们类似,但是 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.

这篇关于从包含特定值的数组中获取对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆