Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find object value in array with Jquery?

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"}]

like image 987
Jroen Avatar asked Aug 31 '11 19:08

Jroen


People also ask

How do I find the value of an array of objects?

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 .

How do you check if an array contains a value in jQuery?

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.

How do you filter an array of objects?

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.


2 Answers

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){
like image 83
Chandu Avatar answered Oct 03 '22 05:10

Chandu


if ( $.inArray(valueToMatch, theArray) > -1 ) 
like image 24
aziz punjani Avatar answered Oct 03 '22 04:10

aziz punjani