2012-04-19 2 views
3

javascriptでは、配列に値が含まれているかどうかを知る必要があります。値はオブジェクトで、同じオブジェクトの異なるインスタンスを持つことができます。つまり、$ .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 

this answerで提供されているように、あなたは、ブール集計関数を使用することができます。

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

あなたの配列をフィルタリングするgreep()機能を使用することができます生成された配列内の項目の数を取得します。しかし、それは配列のすべてを扱います、そして、あなたがたくさんのデータを持っているなら、それはパフォーマンスに優しいものではありません。

0

jquery map関数が問題を解決するはずです。 マップのコールバックで比較ロジックを実装できます。 refer jQuery map

1

あなたはあなたの仕事のために、この機能を使用することがあります。grepを機能付き

$.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:あなたの編集を使うことができました。そのため、 'some()'を提案しました。コールバックが真を返すとすぐに停止します。 – georg

+0

ありがとうございます!それはまさに私が探しているものです – Andris

関連する問題