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.)

Answers:

Answer

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;
   }
}
Answer

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.

Answer

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

var array = [{
    "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);
Answer

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

var numMngrName = 0;

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

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

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

You can iterate over the collection and check each object if it contains the property:

var count = 0;
var i;
for(i = 0; i < jsonObj.length; i += 1) {
    if(jsonObj[i]["MNGR_NAME"]) {
        count++;
    }
}

Working example: http://jsfiddle.net/j3fbQ/

Answer

You could use $.each or $.grep, if you also want to get the elements that contain the attribute.

filtered = $.grep(result, function(value) {
    return (value["MNGR_NAME"] !== undefined)
});
count = filtered.length
Answer

Use ES6...

myobj1.map(items =>
{
if(items.MNGR_NAME) {
return items.MNGR_NAME;
}else {
//do want you want.
}    
})

Thanks.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.