如何从json重建表?

时间:2018-04-02 19:15:34

标签: javascript jquery json

以下几乎正常运作:

var data = [{"Mamma":["Papa","Nonna"],"Hello":["Bye","Yes"]}];

var colHeader = Object.keys(data[0]);

for(var i=0; i<colHeader.length; i++) {
    $('table thead tr').append('<td>' + colHeader[i] + '</td>');
}

for(var i=0; i<data.length; i++){
    $('table tbody').append('<tr></tr>')
    for(var j= 0; j<colHeader.length; j++){
    $('table tbody tr').last().append('<td>' + data[i][colHeader[j]] + '</td>');
  }
}

但是我按照下面的图片得到了td中有两个值的表格

enter image description here

Here it is a jsFIddle

2 个答案:

答案 0 :(得分:1)

您还需要循环对象值,这些值是数组,然后按索引追加。

var data = [{"Mamma": ["Papa", "Nonna"],"Hello": ["Bye", "Yes"]}];

data.forEach(obj => {
  Object.keys(obj).forEach(key => {
    $('thead').append($('<th>').text(key));

    obj[key].forEach((e, i) => {
      if(!$("tbody tr:eq("+i+")").length) $("<tr>").appendTo($("tbody"));
      $("tbody tr:eq(" + i + ")").append($('<td>').text(e))
    })
  })
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <thead></thead>
  <tbody></tbody>
</table>

答案 1 :(得分:1)

请尝试使用此代码段中的示例,并告诉我它是否是预期的输出。

&#13;
&#13;
var data = [{"Hello": ["Bye", "", "", "", "", ""],"h2": ["", "", "", "c", "", "d"]}];

var outerIndex = 0;
$.each(data[0],(key, arr) => {
    $('thead').append($('<th>').text(key));

    data[0][key].forEach((e, i) => {
      if(!$("tbody tr:eq("+i+")").length)
        $("<tr>").appendTo($("tbody"));
        var colIndex = $("tbody tr:eq(" + i + ")").children('td').length;
        while(colIndex++ !== outerIndex){
          $("tbody tr:eq(" + i + ")").append('<td>');
        }
                
      $("tbody tr:eq(" + i + ")").append($('<td>').text(e))
    })
    outerIndex++
})
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
  <thead></thead>
  <tbody></tbody>
</table>
&#13;
&#13;
&#13;