首页 > 解决方案 > jquery从数组动态创建表

问题描述

我目前正在尝试从数组创建一个表。数组的格式如下:

[
  {
    header: 'ID',
    values: [1, 2]
  },
  {
    header: 'First Name',
    values: ['John', 'Jayne']
  },
  {
    header: 'Last Name',
    value: ['Doe', 'Doe']
  }
]

我已经成功地为表格创建了标题,但是对于从这个数组中以这种方式在哪里或如何处理正文中的渲染有点困难。

const exampleArray = [
  {
    header: 'ID',
    values: [1, 2]
  },
  {
    header: 'First Name',
    values: ['John', 'Jayne']
  },
  {
    header: 'Last Name',
    values: ['Doe', 'Doe']
  }
];

const header = $('#results thead tr');
const body = $('#results tbody');

exampleArray.forEach((row) => {
  header.append(
    $(`<th>${row.header}</th>`)
  );
});
<table id="results">
<thead>
<tr>
  <!-- HEADERS -->
</tr>
</thead>
<tbody>

</tbody>
</table>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

我不确定这是否是最好的方法,或者在尝试渲染表格之前是否值得将结果集映射到更可变的东西。

标签: javascriptjquery

解决方案


您调用行中的元素exampleArray,而它们实际上是列。这可能是产生混乱的地方。有关工作示例,请参见下面的代码段。

const exampleArray = [
  {
    header: 'ID',
    values: [1, 2]
  },
  {
    header: 'First Name',
    values: ['John', 'Jayne']
  },
  {
    header: 'Last Name',
    values: ['Doe', 'Doe']
  }
];

const header = $('#results thead tr');
const body = $('#results tbody');

exampleArray.forEach((column) => {
  header.append(
    $(`<th>${column.header}</th>`)
  );
});

// Compute the number of rows in the array
const nRows = exampleArray[0].values.length;

for (let i = 0; i < nRows; i++) {
  // row contains all cells in a row
  let row = $("<tr/>");
  // Loop over the columns
  exampleArray.forEach((column) => {
    // For each column, we add the i-th value, since we're building the i-th row
    row.append(`<td>${column.values[i]}</td>`);
  });
  // Add the row to the table body
  body.append(row);
}
<table id="results">
<thead>
<tr>
  <!-- HEADERS -->
</tr>
</thead>
<tbody>

</tbody>
</table>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


推荐阅读