Sidra Sidra - 2 months ago 6
jQuery Question

Iterate through json object array in jQuery

I am using CodeIgniter. In my Controller file, I have JSON containing an array (as a result of calling different API's):

{
"Specialities": [{
"SpecialityID": 1,
"SpecialityName": "Eye Doctor"
},{
"SpecialityID": 2,
"SpecialityName": "Chiropractor"
},{
"SpecialityID": 3,
"SpecialityName": "Primary Care Doctor"
}]
}


In controller, I wrote

echo $response[0];


with this line of code I can easily iterate through json object in jquery:

$.ajax({
type: 'GET',
url: 'http://localhost/rest_project/main/res',
dataType: 'JSON',
crossDomain: true,
xhrFields: { withCredentials: true },
success: function (data){
$.each(data.Specialities,function(key,value){
console.log(value.SpecialityName);
});
}
});


but if I pass the array:

echo json_encode($response);


Then I am unable to get the results:

$.ajax({
type: 'GET',
url: 'http://localhost/rest_project/main/res',
dataType: 'JSON',
crossDomain: true,
xhrFields: { withCredentials: true },
success: function (data){
$.each(data[0].Specialities,function(key,value){
console.log(value.SpecialityName);
});
}
});


Can someone help me please?

Answer

It seems that your jsonObject is not an array and each works with array only.

//Check if your jsonObject is array, if not then make it.
if (!$.isArray(jsonObject)) {
    jsonObject = [jsonObject];
}

$.each(jsonObject, function(key, value){
  console.log("FULL NAME " + value.FullName);
});

var data = {
    "Specialities": [{
        "SpecialityID": 1,
        "SpecialityName": "Eye Doctor"
    },{
        "SpecialityID": 2,
        "SpecialityName": "Chiropractor"
    },{
        "SpecialityID": 3,
        "SpecialityName": "Primary Care Doctor"
    }] 
};
//Convert your jsonObject to array for each
if (!$.isArray(data)) {
    data = [data];
}
$.each(data[0].Specialities,function(key,value){
   console.log(value.SpecialityName);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Comments