Jquery如何在数组中按属性找到对象 [英] Jquery how to find an Object by attribute in an Array
问题描述
假设我有一个目的对象数组:
//目的对象数组:
var purposeObjects = [
{purpose:daily},
{purpose:weekly},
{purpose:monthly}
]
(为了简单起见,我省略了其他属性)
现在我想有一个方法,如果找到匹配的目的名称,返回一个特定的对象。
这不工作:
function findPurpose
return $ .grep(purposeObjects,function(){
return this.purpose == purposeName;
});
};
findPurpose(daily);
但它实际上返回一个空数组:
[]
我使用的是JQuery 1.5.2。我也试过$ .each(),但没有运气。
显然,大多数JQuery方法是为使用DOM元素而设计的(例如 filter()
。
错误是你不能使用这
function findPurpose ){
return $ .grep(purposeObjects,function(n,i){
return n.purpose == purposeName;
});
};
findPurpose(daily);
返回:
b $ b
[Object {purpose =daily}]
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.
This is not working:
function findPurpose(purposeName){
return $.grep(purposeObjects, function(){
return this.purpose == purposeName;
});
};
findPurpose("daily");
but it actually returns an empty array:
[]
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?
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");
returns:
[Object { purpose="daily"}]
这篇关于Jquery如何在数组中按属性找到对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!