3

I want to check via js/jquery if a value exits in a json array:

[{"pathway_action_fk":"1"},{"pathway_action_fk":"2"},{"pathway_action_fk":"4"}]

I have tried without success:

 $.ajax({
       type: "POST",
       url: "scripts/get_actions_allowed.php",
       data: 'pathway=' + pathway_pk,
      dataType: "json",
       success: function(returnedData) {
if ($.inArray('1', returnedData)){
    $('#script').addClass('active');
}...

If I put in after success:

alert(returnedData);

I get[object Object],[object Object] which is the correct number of objects that should be returned. Removing json as dataType shows the correct values...

4 Answers 4

4

Your array contains JSON objects. So you need to look inside of each object to see if its field has the desired value (or at least, that's what I gather you're trying to do judging by your code).

So perhaps something along the lines of:

$(returnedData).each(function() {
    if (this.pathway_action_fk == 1) {
        $('#script').addClass('active');
    }
});

Example: http://jsfiddle.net/qvsbT/

Sign up to request clarification or add additional context in comments.

Comments

1
$.ajax({
    type: "POST",
    url: "scripts/get_actions_allowed.php",
    data: 'pathway=' + pathway_pk,
    dataType: "json",
    success: function(returnedData)
    {
        for(var i=0, max=returnedData.length; i<max; i++)
        {
            if(returnedData[i].pathwy_action_fk==='1')
            {
                $('#script').addClass('active');
                break;
            }
        }
    }
})

2 Comments

This is just like the original code, you're not looking in the pathway_action_fk property.
Ouch, yeah, sorry. Updated.
1

The elements of the array are objects, not strings. The values you want to check are the pathway_action_fk properties of those objects. So you have to drill down before checking.

if ($.inArray('1', returnedData.map(function(x) {
    return x.pathway_action_fk;
})) != -1);

Also, you need to compare the result of $.inArray with -1 -- it returns the found element's index, which can be 0, not a boolean.

1 Comment

Thanks for this...tried the code but couldn't get it working, though that is probably my failure to implement it properly.
0
  var JSN = 
[
    {
        "email": "[email protected]"
    }, 
    {
        "email": "[email protected]"
    },
    {
        "email": "[email protected]"
    },
    {
        "email": "[email protected]"
    }
];
// var hasMatch =false;
$(JSN).each(function() {
    if (this.email == "[email protected]") {
        alert("found:  " + JSON.stringify(this));
    }else{
        alert('Not Found');

    }

});

Example: https://jsfiddle.net/wfh9ur1j/5/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.