How can I search in an array to see if the value exists?
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);
});
}
So far I tried .is
, .has
, .getdata
and .inarray
, but it's getting me nowhere.
The JSON call returns: [{"fruittype":"special item"},{"fruittype":"blue"},{"fruittype":"red"}]
Checking if Array of Objects Includes Object We can use the some() method to search by object's contents. The some() method takes one argument accepts a callback, which is executed once for each value in the array until it finds an element which meets the condition set by the callback function, and returns true .
The jQuery inArray() method is used to find a specific value in the given array. If the value found, the method returns the index value, i.e., the position of the item. Otherwise, if the value is not present or not found, the inArray() method returns -1.
One can use filter() function in JavaScript to filter the object array based on attributes. The filter() function will return a new array containing all the array elements that pass the given condition. If no elements pass the condition it returns an empty array.
I think its a syntax error:
Change if ($(array.has("special item"))){
to
if ($.inArray("special item", array) > -1){
EDIT:
If the array has complex objects then you cannot use inArray, instead you can use the jQuery filter to achieve the same, e.g:
var filtered = $(array).filter(function(){
return this.fruittype == "special item";
});
if(filtered.length > 0){
if ( $.inArray(valueToMatch, theArray) > -1 )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With