jQuery:如何找到某个属性等于某个值的对象?

jQuery:如何找到某个属性等于某个值的对象?,jquery,Jquery,使用jQuery,如何遍历对象数组并返回满足特定条件的对象?您可以使用以下函数: var matches = jQuery.grep(array, function(item) { // this is a reference to the element in the array // you can do any test on it you want // return true if you want it to be in the resulting match

使用jQuery,如何遍历对象数组并返回满足特定条件的对象?

您可以使用以下函数:

var matches = jQuery.grep(array, function(item) {
    // this is a reference to the element in the array
    // you can do any test on it you want
    // return true if you want it to be in the resulting matches array
    // return false if you don't want it to be in the resulting matches array

    // for example: to find objects with the Amount property set to a certain value
    return(item.Amount === 100);
});
// matches contains all objects that matches
if (matches.length) {
    // first match is in matches[0]
}
如果要测试的条件不是严格相等,则必须使用某种数组迭代来执行自定义比较。您可以使用
.each()
.grep()
执行此操作,具体取决于所需的输出类型

如果条件是严格相等,则可以使用
jQuery.inArray()

显然,您不需要jQuery,因为您可以自己用普通javascript迭代数组,并实现您想要的任何测试。使用纯javascript的一个优点是,当您找到想要的结果时,您可以中断迭代

在常规javascript中:

for (var i = 0, len = array.length; i < len; i++) {
    if (array[i].Price === 100) {
        // match is in array[i]
        break;
    }
}
for(变量i=0,len=array.length;i
这将返回两个2

基本上,数组可以是dom元素的数组,也可以是任何数组,如果它是由jQuery选择器返回的数组,则可以执行以下操作

$('div.someClass').filter(function(){return $(this).hasClass('someOtherClass')})
只为eg->这将返回同时具有someClass和someOtherClass的所有div(注意:有其他方法可以做到这一点)

根据您的评论进行更新,您可以

$(yourArray).filter(function(i,n){return n.Amount && n.Amount == conditionValue;});

您不需要jQuery来完成您需要的工作:

var objects = [{id:23, amount:232}, {id:42, amount: 3434}, ...]

// the function which finds the object you want, pass in a condition function
function findObject(objectMeetsCondition){
     for(var i = 0 ; i < objects.length ; i++){
        if(objectMeetsCondition(objects[i])) return objects[i];
     }
}

// your custom condition that determines whether your object matches
function condition(obj){
   return obj.amount == 3434;
}

findObject(condition); // returns {id:42,amount:3434}
var objects=[{id:23,amount:232},{id:42,amount:3434},…]
//查找所需对象的函数,传入一个条件函数
函数findObject(ObjectMeetCondition){
对于(var i=0;i
这完全取决于对象是什么以及条件是什么。我们需要一些样本数据。你想做什么?你可以发布一些代码>每个对象都有ID和Amount属性。一个数组包含十几个左右的对象。很好,这可以类似地实现为
通用列表/lambda。其中(n=>…)
在C中,根据jQuery文档
绑定到全局窗口对象,而不是项。该项是该函数的第一个参数。@Andy-Thx-I更正了它。
var objects = [{id:23, amount:232}, {id:42, amount: 3434}, ...]

// the function which finds the object you want, pass in a condition function
function findObject(objectMeetsCondition){
     for(var i = 0 ; i < objects.length ; i++){
        if(objectMeetsCondition(objects[i])) return objects[i];
     }
}

// your custom condition that determines whether your object matches
function condition(obj){
   return obj.amount == 3434;
}

findObject(condition); // returns {id:42,amount:3434}