简体   繁体   English

如何迭代一些JSON对象键

[英]How to iterate over some of the JSON object keys

I have a JSON object of the format: 我有一个格式的JSON对象:

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

where there are 64 zones numbered z001 to z064. 其中有64个区域,编号为z001至z064。

What is the best way in Javascript to populate a table based on the "status" of zones z001 to z015? 用Javascript根据区域z001到z015的“状态”填充表的最佳方法是什么? Here is my current code that only evaluates zone z003: 这是我当前的代码,仅评估区域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);

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;
}
 $.getJSON("http://rackserver.local:8080",function(data) {

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

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. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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