Jquery如何通过数组中的属性查找对象 [英] Jquery how to find an Object by attribute in an Array

查看:138
本文介绍了Jquery如何通过数组中的属性查找对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

鉴于我有一组目的"对象:

Given I have an array of "purpose" objects:

//array of purpose objects:
var purposeObjects = [
    {purpose: "daily"},
    {purpose: "weekly"},
    {purpose: "monthly"}
];

(为简单起见,我省略了其他属性)

(for simplicity i am omitting other attributes)

现在我想要一个方法,如果找到匹配的目的名称,它会返回一个特定的对象.

Now I want to have a method that returns a specific one of the objects if a matching purpose name is found.

这不起作用:

function findPurpose(purposeName){
    return $.grep(purposeObjects, function(){
      return this.purpose == purposeName;
    });
};

findPurpose("daily");

但它实际上返回一个空数组:

but it actually returns an empty array:

[]

我使用的是 JQuery 1.5.2.我也试过 $.each() 但没有运气.显然,大多数 JQuery 方法是为与 DOM 元素一起使用而设计的(例如 filter().

I am using JQuery 1.5.2. I have also tried with $.each() but with no luck. Apparently, most JQuery methods are designed for usage with DOM elements (such as filter().

关于如何实现这一目标的任何想法?

Any ideas on how to achieve this?

推荐答案

错误是不能在 grep 中使用 this,但必须使用对元素的引用.这有效:

The error was that you cannot use this in the grep, but you must use a reference to the element. This works:

function findPurpose(purposeName){
    return $.grep(purposeObjects, function(n, i){
      return n.purpose == purposeName;
    });
};

findPurpose("daily");

返回:

[Object { purpose="daily"}]

这篇关于Jquery如何通过数组中的属性查找对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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