How to loop through JSON array?

I have some JSON-code which has multiple objects in it:

[
    {
        "MNGR_NAME": "Mark",
        "MGR_ID": "M44",
        "EMP_ID": "1849"
    },
    {
        "MNGR_NAME": "Steve",
        "PROJ_ID": "88421",
        "PROJ_NAME": "ABC",
        "PROJ_ALLOC_NO": "49"
    }
]

My JSON loop snippet is:

function ServiceSucceeded(result) 
{       
  for(var x=0; x<result.length; x++) 
  {      

  }    
}

Could you please let me know how to check there is no occurence of "MNGR_NAME" in the array. (It appears twice in my case.)


Solution 1:

You need to access the result object on iteration.

for (var key in result)
{
   if (result.hasOwnProperty(key))
   {
      // here you have access to
      var MNGR_NAME = result[key].MNGR_NAME;
      var MGR_ID = result[key].MGR_ID;
   }
}

Solution 2:

You could use jQuery's $.each:

    var exists = false;

    $.each(arr, function(index, obj){
       if(typeof(obj.MNGR_NAME) !== 'undefined'){
          exists = true;
          return false;
       }
    });

    alert('Does a manager exists? ' + exists);

Returning false will break the each, so when one manager is encountered, the iteration will stop.