如何实现循环打印的唯一身份?

我试图循环JSON格式,但是它没能运行起来。当我正确地循环"id_first" print 1 和 2 时,循环调用仍然没有定义ID。如何实现循环打印的唯一身份?

我的代码:

$(document).ready(function() {
   $.ajax({
     url: "http://192.168.1.190/tmp/data.json",
     method: "GET",
     success: function(data) {
       var id_first = [];

       for (var i in data) {
         id_first.push(data[i].id_first);
         alert(data[i].id_first);
       }
     },
     error: function(data) {
       console.log('error');
     }
   });
});

数据:

 [{
   "id_first": "1",
   "data_first": "1"
 }, {
   "id_first": "2",
   "data_first": "2"
 }, {
   "id_second": "1",
   "data_second": "1"
 }, {
   "id_second": "2",
   "data_second": "2"
 }]

Check whether id_first exist with data[i].id_first != undefined inside loop if yes then push into Array. So only valid(not undefined) will be added to id_first array

 var id_first=[]
var data =  [{
    "id_first": "1",
    "data_first": "1"   }, {
    "id_first": "2",
    "data_first": "2"  },  {
    "id_second": "1",
    "data_second": "1"  }, {
    "id_second": "2",
    "data_second": "2"  }]
     for(var i in data) {
     if(data[i].id_first != undefined){
          id_first.push(data[i].id_first);
          alert(data[i].id_first);
          }
     }
      console.log(id_first);

</div>

First check whether "id_first" property is exists in the JSON object or not, if exists then push it into the array otherwise skip it.

$(document).ready(function(){
    $.ajax({
        url: "http://192.168.1.190/tmp/data.json", 
        method: "GET", 
        success: function(data) {
          var id_first=[]

          for(var i in data) {

             if(data[i].id_first){
                  id_first.push(data[i].id_first);
                  alert(data[i].id_first);
             }

          }

        },  
        error: function(data) {
            console.log('error');
        }
    });
  });

undefined means that the property you want to access is not available or not defined.

Hence, to overcome from this problem you have to check whether property is exists in the object or not before pushing it into the array.

DEMO

$(document).ready(function() {
    $.ajax({
        url: "http://192.168.1.190/tmp/data.json", 
        method: "GET", 
        success: function(data) {
          var id_first=[];
          for(var i in data) {
             if(data[i].id_first) {
               id_first.push(data[i].id_first);
             }

          }

        },  
        error: function(data) {
            console.log('error');
        }
    });
});