0

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);
gdoron
  • 147,333
  • 58
  • 291
  • 367
user142512
  • 87
  • 1
  • 4
  • [This](http://stackoverflow.com/questions/684672/loop-through-javascript-object) question may be similar to your question. – yondoo Jan 25 '13 at 02:32

3 Answers3

1

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;
}
gdoron
  • 147,333
  • 58
  • 291
  • 367
  • `What is the best way in Javascript to populate a table based on the "status" of zones z001 to z015?` – Ian Jan 25 '13 at 02:50
  • This isn't my question. I was merely trying to point out that the OP was asking for 1 to 15, not 64...I should've been more direct. Anyways, there aren't 2 questions in this thread, so I'm not sure what you mean – Ian Jan 25 '13 at 02:56
0
 $.getJSON("http://rackserver.local:8080",function(data) {

$.each( data, function( key, value ) {
  if (data[key].status != "restored") {
//do your stuff
} else {
//do more stuff
}
});
Michal
  • 13,439
  • 3
  • 35
  • 33
0

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.

Chandu Dexter
  • 456
  • 2
  • 4