简体   繁体   中英

Looping through dynamic JSON data using javascript

I am trying to display JSON data but the key value is dynamic it varies from one POST request to another my data hierarchy is as shown in diagram:

This is the part of the code I am running,Can anyone suggest me how to display JSON data where key showed in redbox gonna change for every POST request

$.ajax({
  type: "POST",
  url: "/",
  dataType:'json',
  data : { 'perfid': valueOne, 'hostname': $("#host").val(), 'iteration': valueThree},
  success: function(data) {
    $('#img1').hide();
    var k = data[$("#host").val()].iscsi_lif.result.sectoutput.sect.length; 
    for(var i = 0; i < k; i++) {
                var obj = k[i];
                console.log(obj);
                var iscsi =  parseInt(data[$("#host").val()].iscsi_lif.result.sectoutput.sect.obj.avg_latency);
console.log(iscsi);
             }

While running above snippet I am getting following error message :

data[$(....).val(...)].iscsi_lif.result.sectoutput.sect is undefined

You can use a "for in" loop to iterate over the keys of an object without having to specify the key names.

for( var key in myObject){
  myValue = myObject[key];
  // key will be your dynamically created keyname
}

So your code could be similar to the following:

...  
success: function(data) {
  $('#img1').hide();
  var obj = data[$("#host").val()].iscsi_lif.result.sectoutput.sect; 
  for(var key in obj) {
    if(obj.hasOwnProperty(key)){
      var iscsi = parseInt(obj[key].avg_latency);
      console.log(iscsi);
    }
  }
}

Solution Suggestion:

for (var key in object) {
    if (object.hasOwnProperty(key)) {
        var element = object[key];

    }
}

Yet, in your situation, maybe you'll have to do this multiple times, so I would try to extract a generic function to do this and "normalize" the processing result to an expected format that wouldn't change.

The function will only run when the expected keys exist and since the forin loop uses the object keys, every object is processed dynamically.

This should work:

var k = data[$("#host").val()].iscsi_lif.result.sectoutput.sect;
for (var i = 0; i < k.length; i++) {
  var obj = k[i];
  console.log(obj);
  var iscsi = parseInt(data[$("#host").val()].iscsi_lif.result.sectoutput.sect[obj].avg_latency);
  console.log(iscsi);
}

The variable should be put inside brackets. Also, it seemed to me that k was simply defined as length of an array, I removed that and put it to the for loop.

Since you have obj defined as varible you should use [] , so it will be [obj] , eg :

var iscsi =  parseInt(data[$("#host").val()].iscsi_lif.result.sectoutput.sect[obj].avg_latency);

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM