2012-04-19 2 views
3

자바 스크립트에서 배열에 값이 들어 있는지 알아야합니다. 값은 객체이며 동일한 객체의 다른 인스턴스를 가질 수 있습니다. 즉, $ .inArray (...)가 작동하지 않습니다. $ .each (...)를 사용하여 작업을 수행하는 방법을 알고 있고 내 질문은 - 값을 비교 논리로 함수를 jQuery 메서드에 전달할 수 있습니까 (원하는 sintax가있는 샘플 참조)?jQuery 배열에서 값을 검색하기위한 기준을 지정하십시오.

// values 
var val1 = { id: 1, description: 'First value'}; 
var val2 = { id: 2, description: 'Second value'}; 
var val3 = { id: 3, description: 'Third value'};   
// array of values 
var values = [ val1, val2, val3 ]; 
// inArray of jQuery to know if value is in array -> returns TRUE 
var isInArray = $.inArray(val2, values) > -1; 

// another instance of same object "val2" 
var val2_anotherInstance = { id: 2, description: 'Second value'}; 
// inArray works as expected -> returns FALSE but desirable result is TRUE 
var isInArray_anotherInstance = $.inArray(val2_anotherInstance, values) > -1; 

// define function for comparing values (any logic can be implemented, for example searching by Id) 
var valueComparer = function(first, second) { 
    return first.id == second.id && first.description == second.description; 
} 
// function compares objects and returns true for different instances 
alert(valueComparer(val2, val2_anotherInstance)); 

// desirable sintax: 
// is something like this possible ???  
// NOTE next line not correct 
isInArray_anotherInstance = $.inArray(val2_anotherInstance, values, valueComparer) > -1; 
// actually what I want is specify criteria for searching value in array 
+0

불행히도'inArray()'는 함수를 사용하지 않습니다. 'grep()' – elclanrs

답변

2

grep을 시도해보십시오

var val1 = { id: 1, description: 'First value'}; 
var val2 = { id: 2, description: 'Second value'}; 
var val3 = { id: 3, description: 'Third value'};   

var values = [ val1, val2, val3 ]; 

// another instance of same object "val2" 
var val2_anotherInstance = { id: 2, description: 'Second value'}; 


var items = $.grep(values, function(x) { 
    return x.id == val2_anotherInstance.id 
}) 

var found = items.length > 0 

더 우아함를 들어, 부울 애그리 게이터 (aggregator) 기능을 사용할 수 있습니다 this answer에 규정 :

val2_in_array = $.some(values, function() { 
    return this.id == val2_anotherInstance.id 
}); 
0

당신은 당신의 배열을 필터링 할 greep() 기능을 사용할 수 있습니다 생성 된 배열의 항목 수를 가져옵니다. 그러나 모든 배열을 처리 할 것이고 많은 양의 데이터를 가지고 있다면 성능이 좋지 않을 것입니다.

0

jquery map 함수가 문제를 해결해야합니다. 지도의 콜백에 비교 논리를 구현할 수 있습니다. refer jQuery map

1

당신은 당신의 작업에이 기능을 사용할 수 있습니다 : 그렙 기능

$.fn.inArrayCallback = function(needle, haystack, f) { 
    var e = -1; 
    $.each(haystack,function(index, value){ 
     if (f(needle,value)) { e = index; return false; } 
    }); 
    return e; 
} 

ans = $.fn.inArrayCallback(val2_anotherInstance, values, valueComparer) > -1; 
// returns true 

대답이 일치하는 요소가 이미 발견 된 경우에도, 배열의 모든 요소를 ​​검색합니다. 이 함수는 검색시 검색을 중지합니다. 이것은 매우 큰 배열에서 중요 할 수 있습니다.

+0

re : 귀하의 편집을 사용할 수 있습니다. 그래서 콜백이 true를 리턴하자마자 멈추는'some()'을 제안했습니다. – georg

+0

감사합니다 !! 그게 내가 원하는거야. – Andris

관련 문제