2011-08-31 4 views
8

¿Cómo puedo buscar en una matriz para ver si el valor existe?¿Cómo encontrar el valor del objeto en la matriz 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); 
      }); 
} 

Hasta ahora he intentado .is, .has, .getdata y .inarray, pero me está llegando a ninguna parte.

La llamada devuelve JSON: [{"fruittype":"special item"},{"fruittype":"blue"},{"fruittype":"red"}]

+0

¿Cómo es su matriz? –

Respuesta

24

Creo que es un error de sintaxis: Cambio if ($(array.has("special item"))){ a

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

EDIT:

Si la matriz tiene objetos complejos entonces no puedes usar inArray, en vez de eso Puede usar el filtro jQuery para lograr lo mismo, por ejemplo:

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

Aunque la respuesta se muestra dos veces aquí, esto no parece funcionar. – Jroen

+0

¿Se puede publicar la matriz que devuelve la llamada JSON? – Chandu

+0

La llamada JSON devuelve: '[{" fruittype ":" elemento especial "}, {" fruittype ":" blue "}, {" fruittype ":" red "}]' – Jroen

2
if ($.inArray(valueToMatch, theArray) > -1) 
Cuestiones relacionadas