2012-03-09 5 views
8

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

는, 당신은 배열의 어떤 종류를 사용해야합니다 :

+1

이는 개체의 상태와 상태에 따라 다릅니다. 샘플 데이터가 필요합니다. –

+0

무엇을하려고합니까? 코드를 게시 할 수 있습니까? – elclanrs

+0

각 개체에는 ID 및 금액 속성이 있습니다. 배열은 12 개 정도의 객체를 포함합니다. – David

답변

14

당신은 jQuery grep 기능을 사용할 수 있습니다 . 원하는 출력 유형에 따라 .each() 또는 .grep()으로 처리 할 수 ​​있습니다.

조건이 동일하면 jQuery.inArray()을 사용할 수 있습니다.

당연히 jQuery가 필요하지는 않습니다. 보통 자바 스크립트에서 직접 배열을 반복하고 원하는 테스트를 구현할 수 있습니다. 일반 자바 스크립트를 사용하면 얻을 수있는 이점 중 하나는 원하는 결과를 찾았을 때 반복을 벗어날 수 있다는 것입니다. 일반 자바 스크립트에서

:

for (var i = 0, len = array.length; i < len; i++) { 
    if (array[i].Price === 100) { 
     // match is in array[i] 
     break; 
    } 
} 
+0

Nice, 이것은 C# – Pierre

+0

에서'Generic Lists/lambda .Where (n => ...) '와 유사하게 구현 될 수 있습니다. jQuery 문서에 따르면'''this'''는 전역 윈도우 객체에 바인딩되지만 목. 항목은 해당 함수의 첫 번째 매개 변수입니다. – Andy

+0

@Andy - Thx - 수정했습니다. – jfriend00

1
$([1,2,2,4]).filter(function(i,n){return n==2;}); 

이이 사실 기본적으로 배열 DOM 요소 또는 배열의 배열이 될 수 모두 2의

를 반환합니다 그것은에 의해 반환 된 배열 인 경우 jQuery selector 같은 것을 할 수 있습니다.

$('div.someClass').filter(function(){return $(this).hasClass('someOtherClass')}) 

예 :> 이것은 다음과 같은 모든 div를 반환합니다. someClass 및 someOtherClass (참고 :이 작업을 수행하는 다른 방법이있다) 모두를했습니다 당신은 정말 당신이 필요로 할 jQuery를 필요가 없습니다

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

의견에 따라

업데이트, 당신은 할 수 있습니다 :

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} 
관련 문제