【问题标题】:Convert array to HTML table on specific column将数组转换为特定列上的 HTML 表
【发布时间】:2021-05-11 03:04:03
【问题描述】:

我想将一个嵌套数组转换为一个 HTML 表格,我在其中分配了table_header

同样,Column_1 中的第一个子数组和Column_2 中的第二个子数组。

const arr = [
  [
    "abc",
    "gsdg",
    "fsvth",
    "rewurths",
    "ejgfjsgfns",
    "sdbqeqtjhbq"
  ],
  [
    "ryethabe"
  ]
]
<table id="table">
  <thead>
    <tr>
      <th>Column_1</th>
      <th>Column_2</th>
    </tr>
  </thead>
  <tbody id="table_data_response">
  </tbody>
</table>

【问题讨论】:

  • 也许 Stack Overflow 上另一篇帖子的以下答案满足您的需求:stackoverflow.com/a/51276151/3272066(具体来说,答案中的函数append_json)。
  • 我修复了你的表格 html。它无效 - 预期的输出是什么?画一张图并展示你尝试过的 JavaScript

标签: javascript html html-table


【解决方案1】:

实际上你有一个二维数组。您可以在嵌套的 for 循环中构建结果字符串并动态构建表格,然后将其插入到 DOM 元素中。

我给你做了一个sn-p。

const obj = [
  [
    "abc",
    "gsdg",
    "fsvth",
    "rewurths",
    "ejgfjsgfns",
    "sdbqeqtjhbq"
  ],
  [
    "ryethabe"
  ]
]

let resString = '<table><thead><tr><th>Col1</th><th>Col2</th></tr></thead><tbody>';

// Calculate which array has the bigger size, this is needed as running condition in the outer for-loop
let max;
obj[0].length > obj[1].length ? max = obj[0].length : max = obj[1].length;


for (let i = 0; i < max; i++) {
  resString += '<tr>';
  for (let j = 0; j < obj.length; j++) {
    if (obj[j][i] !== null && obj[j][i] !== undefined) {
        resString += `<td>${obj[j][i]}</td>`
      }
    }
    resString += '</tr>';
  }

  resString += '</tbody></table>';


  document.getElementById('bla').innerHTML = resString;
&lt;div id="bla"&gt; &lt;/div&gt;

【讨论】:

    【解决方案2】:

    也许是这个?

    const arr = [ ["abc", "gsdg", "fsvth", "rewurths", "ejgfjsgfns", "sdbqeqtjhbq"],  ["ryethabe"] ];
    
    document.getElementById("table_data_response").innerHTML = ['<tr>', 
      ...arr.reduce((acc, item, i) => {
        const row = (acc[i] || '<td>') + item.join('<br/>') + '</td>';
        acc.push(row);
        return acc;
      }, []), '</tr>'].join("");
    <table id="table">
      <thead>
        <tr>
          <th>Column_1</th>
          <th>Column_2</th>
        </tr>
      </thead>
      <tbody id="table_data_response">
      </tbody>
    </table>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-04-10
      • 1970-01-01
      • 1970-01-01
      • 2019-09-27
      • 1970-01-01
      • 1970-01-01
      • 2015-03-26
      • 2021-05-06
      相关资源
      最近更新 更多