user142512
user142512

Reputation: 87

How to iterate over some of the JSON object keys

I have a JSON object of the format:

{
    "z061": {
        "status": "restored",
        "time": 135
    },
    "z039": {
        "status": "restored",
        "time": 139
    }, ...
}

where there are 64 zones numbered z001 to z064.

What is the best way in Javascript to populate a table based on the "status" of zones z001 to z015? Here is my current code that only evaluates zone z003:

      setInterval(function() {
        $.getJSON("http://rackserver.local:8080",function(data) {
          var temp = data.z003.status;
          if (temp != "restored")
            $("#securityTable tr:eq(3)").removeClass("error").addClass("success");
          else
            $("#securityTable tr:eq(3)").removeClass("success").addClass("error");
          });
        }, 1500);

Upvotes: 0

Views: 321

Answers (3)

Chandu Dexter
Chandu Dexter

Reputation: 456

Here is the code I came up with.

setInterval(function() {
  $.getJSON("http://rackserver.local:8080",function(data) {
    var i = 1, j;
    for (; i <= 64; i += 1) {
      j = 'z';
      if (i < 10)  j += '0';
      if (i < 100) j += '0';
      if (data[j + i].status !== "restored")
        $("#securityTable tr:eq(" + i + ")").removeClass("error").addClass("success");
      else
        $("#securityTable tr:eq(" + i + ")").removeClass("success").addClass("error");
    }
  }, 1500);

Hope this helps.

Upvotes: 0

gdoron
gdoron

Reputation: 150263

You can access objects with the dot operator or with the indexers operator, this task is for the indexers.

for (var i = 1; i <=15; i++){
    // hardcoded the check to make it easier.
    if (i >= 10) 
        var temp = data["z0" + i].status;
    else
        var temp = data["z00" + i].status;
}

Upvotes: 1

Michal
Michal

Reputation: 13639

 $.getJSON("http://rackserver.local:8080",function(data) {

$.each( data, function( key, value ) {
  if (data[key].status != "restored") {
//do your stuff
} else {
//do more stuff
}
});

Upvotes: 0

Related Questions