Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 540
pal Avatar asked Dec 13 '11 12:12

pal


People also ask

Is looping an array is possible in JSON?

Looping Using JSON JSON stands for JavaScript Object Notation. It's a light format for storing and transferring data from one place to another. So in looping, it is one of the most commonly used techniques for transporting data that is the array format or in attribute values.

How do I iterate through a JSON object?

Use Object. values() or Object. entries(). These will return an array which we can then iterate over. Note that the const [key, value] = entry; syntax is an example of array destructuring that was introduced to the language in ES2015.

How do I traverse a JSON array?

1) Create a Maven project and add json dependency in POM. xml file. 2) Create a string of JSON data which we convert into JSON object to manipulate its data. 3) After that, we get the JSON Array from the JSON Object using getJSONArray() method and store it into a variable of type JSONArray.

How do I iterate JSON in HTML?

forEach() function. This can be further optimized by having that giant html string hidden in a script tag with type="text/x-template" (since the browser ignores script types it doesn't understand) and grabbing it with the innerHTML function by referencing the id property on the script tag.


2 Answers

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;
   }
}
like image 190
Abdul Munim Avatar answered Oct 10 '22 17:10

Abdul Munim


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.

like image 36
Kees C. Bakker Avatar answered Oct 10 '22 17:10

Kees C. Bakker