How to loop through JSON array?

前端 未结 8 1634
鱼传尺愫
鱼传尺愫 2020-12-01 14:52

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

[
    {
        \"MNGR_NAME\": \"Mark\",
        \"MGR_ID\": \"M44\",
        \"EMP_ID\": \"1849\"
           


        
相关标签:
8条回答
  • 2020-12-01 15:27

    Use ES6...

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

    Thanks.

    0 讨论(0)
  • 2020-12-01 15:30

    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);
    }
    
    0 讨论(0)
  • 2020-12-01 15:30

    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
    
    0 讨论(0)
  • 2020-12-01 15:32

    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++;
        }
    });
    
    0 讨论(0)
  • 2020-12-01 15:36

    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);
    
    0 讨论(0)
  • 2020-12-01 15:41

    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.

    0 讨论(0)
提交回复
热议问题