使用JavaScript数组填充HTML表格

3

我有一个类似于以下的脚本数组:

var lakeData = [
{
   "Month": "1959-01",
   "LakeErieLevels": 12.296
 },
 {
   "Month": "1959-02",
   "LakeErieLevels": 13.131
 },
 {
   "Month": "1959-03",
   "LakeErieLevels": 13.966
 },
 {
   "Month": "1959-04",
   "LakeErieLevels": 15.028
 },
 {
   "Month": "1959-05",
   "LakeErieLevels": 15.844
 },
 {
   "Month": "1959-06",
   "LakeErieLevels": 15.769
 }
 ];

以下是一些HTML代码:

<table id="lake">
  <thead><tr><th>Date</th><th>Depth</th></tr></thead>
  <tbody></tbody>
</table>

我正在尝试在页面加载时将数组填充到表格中。


有很多适用于此的JavaScript库.. https://datatables.net/examples/data_sources/js_array.html。您的问题没有显示任何(重新)搜索的努力或尝试解决它,而您已经得到了答案https://stackoverflow.com/questions/47482073/putting-array-into-an-html-table-and-ascending-or-descending-them - Slai
1个回答

6

var lakeData = [{
    "Month": "1959-01",
    "LakeErieLevels": 12.296
  },
  {
    "Month": "1959-02",
    "LakeErieLevels": 13.131
  },
  {
    "Month": "1959-03",
    "LakeErieLevels": 13.966
  },
  {
    "Month": "1959-04",
    "LakeErieLevels": 15.028
  },
  {
    "Month": "1959-05",
    "LakeErieLevels": 15.844
  },
  {
    "Month": "1959-06",
    "LakeErieLevels": 15.769
  }
];

function addDataToTbody(nl, data) { // nl -> NodeList, data -> array with objects
  data.forEach((d, i) => {
    var tr = nl.insertRow(i);
    Object.keys(d).forEach((k, j) => { // Keys from object represent th.innerHTML
      var cell = tr.insertCell(j);
      cell.innerHTML = d[k]; // Assign object values to cells   
    });
    nl.appendChild(tr);
  })
}

var lakeTbody = document.querySelector("#lake tbody");

addDataToTbody(lakeTbody, lakeData);
<table id="lake">
  <thead>
    <tr>
      <th>Date</th>
      <th>Depth</th>
    </tr>
  </thead>
  <tbody></tbody>
</table>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接