Skip to content Skip to sidebar Skip to footer

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': 'St

Solution 1:

You need to access the result object on iteration.

for (var key in result)
{
   if (result.hasOwnProperty(key))
   {
      // here you have access tovar 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;
          returnfalse;
       }
    });

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

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

Solution 3:

Note that your object is an array of JavaScript objects. Could you use something like this?

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

var numberOfMngrName = 0;
for(var i=0;i<array.length;i++){
    if(array[i].MNGR_NAME != null){
        numberOfMngrName++;
    }
}

console.log(numberOfMngrName);

Solution 4:

This will find the number of occurrences of the MNGR_NAME key in your ObjectArray:

var numMngrName = 0;

$.each(json, function () {
    // 'this' is the Object you are iterating overif (this.MNGR_NAME !== undefined) {
        numMngrName++;
    }
});

Solution 5:

Within the loop result[x] is the object, so if you wanted to count a member that may or may not be present;

functionServiceSucceeded(result)
{
  var managers = 0for(var x=0; x<result.length; x++)
  {
        if (typeof result[x].MNGR_NAME !== "undefined")
            managers++;
  }
  alert(managers);
}

Post a Comment for "How To Loop Through Json Array?"