Tsea Tsea - 1 month ago 8
Ajax Question

How to search an array of objects in jquery

I'm using ajax to get this array of objects returned to me. I'm trying to check to see if user email matches the one given by user also want to check to see if id is not null

Array ( [success] => 1
[data] => Array (

[0] => Array ( [id] => 1 [firstName] => Juan [lastName] => Laxague [fullName] => Juan Manuel Laxague [email] => julx@iloud.com )

[1] => Array ( [id] => 3 [firstName] => test [lastName] => test123 [fullName] => test test123 [email] => tes1234@mytst.com )

[2] => Array ( [id] => 4 [firstName] => Mike [lastName] => V [fullName] => Mike V [email] => jar_k@yaoo.com )

))

$.ajax({
url: 'https://url,org/api/users/',
datatype:"json",
type: "GET",
headers: {
'Content-Type' : 'application/json',
'Access-Token' : 'CWku8OSq0w'
},
success:function(data){
console.log(data);

$.each(data, function (i, item) {
var a = item.email;
var b = item.id;
if (a == "useremail@nn.com" && b != null){
alert("success!");
}
});
},
error: function(e) {

console.log(e);

},
});
});


If I do
item[0]
it works for one result. How do I get it to check every result in the array of objects?

Answer

Inside of your result object (i.e. data), there's an object with a property named data which contains your actual results. You can iterate over the results using $.each as you are doing, but make sure you're iterating over the actual array that you care about (data["data"]):

success:function(data){
    console.log(data);

    $.each(data["data"], function (i, item) {
      var a = item.email;
      var b = item.id;
         if (a == "useremail@nn.com" && b != null){
                alert("success!");
         }
    });
}

You might consider renaming your results variable to avoid confusion around which data you're referring to.