2011-08-31 10 views
8

Come posso cercare in una matrice per vedere se il valore esiste?Come trovare il valore dell'oggetto nella matrice con Jquery?

var fruitVarietyChecked = $('input[name=fruitVariety]:checked').val(); 

$.getJSON('getdata.php', {fruitVariety: fruitVarietyChecked}, function(fruittype) { 

      var html = ''; 
      $.each(fruittype, function(index, array) { 

       alert("Key: " + index + ", Value: " + array['fruittype']); 
       //shows array - Key: 0 , Value: special item 

       //this is where the problem is 
       if ($(array.has("special item"))){ 

        $("p").text("special item" + " found at " + index); 
        return false; 
        } 

       html = html + '<label><input type="radio" name="fruitType" value="' + array['fruittype'] + '" />' + array['fruittype'] + '</label> '; 
      }); 
      $('#fruittype').html(html); 
      }); 
} 

Finora ho provato .is, .has, .getdata e .inarray, ma mi sta andando da nessuna parte.

La chiamata JSON restituisce: [{"fruittype":"special item"},{"fruittype":"blue"},{"fruittype":"red"}]

+0

Che aspetto ha il tuo array? –

risposta

24

Penso che sia un errore di sintassi: Change if ($(array.has("special item"))){ a

if ($.inArray("special item", array) > -1){ 

EDIT:

Se l'array ha oggetti complessi quindi non puoi usare inArray, invece yo Puoi utilizzare il filtro jQuery per ottenere lo stesso risultato, ad esempio:

var filtered = $(array).filter(function(){ 
     return this.fruittype == "special item"; 
    }); 
    if(filtered.length > 0){ 
+0

Sebbene la risposta venga mostrata due volte qui, sembra che non funzioni. – Jroen

+0

È possibile pubblicare l'array restituito dalla chiamata JSON? – Chandu

+0

La chiamata JSON restituisce: '[{" fruittype ":" oggetto speciale "}, {" tipo frutta ":" blu "}, {" tipo frutta ":" rosso "}]' – Jroen

2
if ($.inArray(valueToMatch, theArray) > -1) 
Problemi correlati