如何使用JSON数组填充Javascript表?

时间:2015-09-09 04:28:29

标签: javascript jquery

我有类似的JSON数组:

{"X":[
    {"Time":"05:45","Count":70},
    {"Time":"06:30","Count":40},
    {"Time":"08:15","Count":80}
]},
{"Y":[
    {"Time":"09:15","Count":70},
    {"Time":"10:30","Count":84},
    {"Time":"12:00","Count":95}
]},
{"Z":[
    {"Time":"14:00","Count":80},
    {"Time":"16:00","Count":70},
    {"Time":"15:00","Count":40}
]}

我必须动态填充这样的表:

Name    05:45   06:30   08:15   09:15   10:30   12:00   14:00   16:00   15:00

  X       70      40       80     0       0       0       0       0       0
  Y        0       0        0     70     84       95      0       0       0 
  Z        0       0        0     0       0       0       80      70      40

我不知道如何将其填充为Javascript表。有人可以帮帮我吗?

1 个答案:

答案 0 :(得分:1)

使用JSON.parse(//你的json字符串)。 现在你可以通过循环遍历这个json数组来动态创建行 -

 var DataArray = JSON.parse(data.d);
      var tableelement = $("#DataSetTbl");        //get table id from jquery

        tableelement.append(createRow(DataArray));            //call this function from the action you want to show table

    function createRow(Object) {                              //dynamically adding rows to the Table

        var trElement = "<tr>";                 //design this according to your requirement

  for(var s=0;s<Object.length; s++)
        trElement += "<td >" + Object[s].Time + "</td>";


        return trElement;
    }

同样为count添加一个新行:)