The problem

我try 循环遍历一个包含嵌套行的表,并将所有数据导出到CSV.以下是数据 struct :

  • 配置文件
  • 配置文件 > Linked users

数据来自API,它是一个包含嵌套对象的数组,然后我循环这些对象并将其输出到视图.

My attempt

我的当前逻辑部分工作,但将任何具有嵌套行的表行解释为一个组合行.

我可以循环遍历表行,但不能排除组合的行,因此我得到以下输出:

Current result

  • 汤姆
  • 汤姆 杰克 萨姆 亚历克斯 (combined)
  • 杰克
  • 萨姆
  • 亚历克斯
  • 乔什

Expected result

  • 汤姆
  • 杰克
  • 萨姆
  • 亚历克斯
  • 乔什

Codepen example

下面是一个记录输出的基本示例:https://codepen.io/joshuarobertson/pen/xxQjmgV

Table data structure

这是表 struct 的基本示例:

/*
 ** Export table data to CSV
 */
function exportToCsv() {
  // Get the table element
  var table = document.querySelector('table')

  // Create an empty array to store the cell values
  var cellValues = []

  // Get the table headers from the thead section
  var headerValues = []

  table.querySelectorAll('thead th').forEach(function(header) {
    headerValues.push(header.textContent.trim())
  })

  // Add the header values to the main cell values array
  cellValues.push(headerValues.join(','));

  // Function to process the rows recursively
  function processRows(rows) {
    rows.forEach(function(row) {
      var rowValues = []

      // Check if the row has nested tables
      var nestedTables = row.querySelectorAll('table');

      if (nestedTables.length > 0) {
        // Process nested tables recursively
        nestedTables.forEach(function(nestedTable) {
          var nestedRows = nestedTable.querySelectorAll('tr')
          console.log(nestedRows[0].innerText)
          console.log(nestedRows[1].innerText)
          console.log(nestedRows[2].innerText)
          processRows(nestedRows)
        });
      } else {
        // Loop over each cell of the row
        row.querySelectorAll('td').forEach(function(cell) {
          rowValues.push(cell.textContent.trim())
        });

        // Add the row values to the main cell values array
        cellValues.push(rowValues.join(','))
      }
    })
  }

  // Process the top-level table rows
  var topRows = table.querySelectorAll('tbody tr')
  processRows(topRows)

  // Log the comma-separated list to the console
  console.log(cellValues.join('\n'))


  // Combine each row data with new line character
  csv_data = csv_data.join('\n')

  // Call this function to download csv file
  downloadCsv(csv_data)
}

/*
 ** Download CSV
 */
function downloadCsv(csv_data) {

  // Create CSV file object and feed
  // our csv_data into it
  csv_data = new Blob([csv_data], {
    type: "text/csv"
  })

  // Create to temporary link to initiate
  // download process
  const temp_link = document.createElement('a')

  // Download csv file
  temp_link.download = "GfG.csv"
  const url = window.URL.createObjectURL(csv_data)
  temp_link.href = url

  // This link should not be displayed
  temp_link.style.display = "none"
  document.body.appendChild(temp_link)

  // Automatically click the link to
  // trigger download
  temp_link.click()
  document.body.removeChild(temp_link)
}
<table border="1" cellspacing="0" cellpadding="10">
  <thead>
    <tr>
      <th>Name</th>
      <th>Age</th>
      <th>Town</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>汤姆</td>
      <td>20</td>
      <td>London</td>
    </tr>
    <tr>
      <td colspan="3">
        <table>
          <tbody>
            <tr>
              <td>杰克</td>
              <td>30</td>
              <td>Glasgow</td>
            </tr>
          </tbody>
          <tbody>
            <tr>
              <td>萨姆</td>
              <td>40</td>
              <td>Belfast</td>
            </tr>
            <tr>
              <td>亚历克斯</td>
              <td>50</td>
              <td>Hull</td>
            </tr>
          </tbody>
        </table>
      </td>
    </tr>
    <tr>
      <td>乔什</td>
      <td>20</td>
      <td>Cardiff</td>
    </tr>
  </tbody>
</table>

推荐答案

此代码基于html生成CSV,并对具有3个条目的结果进行过滤

const headers = [...document.querySelector('thead tr').children]
  .map(c => c.textContent)

const data = [...document.querySelectorAll('tbody tr')]
  .map(tr => [...tr.children]
    .map(c => c.textContent))
  .filter(c => c.length === 3)

const csv = [headers, ...data].join('\n')

console.log(csv)
<table border="1" cellspacing="0" cellpadding="10">
    <thead>
        <tr>
            <th>Name</th>
            <th>Age</th>
            <th>Town</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>Tom</td>
            <td>20</td>
            <td>London</td>
        </tr>
        <tr>
            <td colspan="3">
                <table>
                    <tbody>
                        <tr>
                            <td>Jack</td>
                            <td>30</td>
                            <td>Glasgow</td>
                        </tr>
                    </tbody>
                    <tbody>
                        <tr>
                            <td>Sam</td>
                            <td>40</td>
                            <td>Belfast</td>
                        </tr>
                        <tr>
                            <td>Alex</td>
                            <td>50</td>
                            <td>Hull</td>
                        </tr>
                    </tbody>
                </table>
            </td>
        </tr>
        <tr>
            <td>Josh</td>
            <td>20</td>
            <td>Cardiff</td>
        </tr>
    </tbody>
</table>

Javascript相关问答推荐

如何使用3个部件之间的路由?

未使用Outlet渲染子组件

为什么有些库公开了执行相同任务的方法,但每个方法都处于同步/同步上下文中?

如何在使用fast-xml-parser构建ML时包括属性值?

我试图实现用户验证的reduxstore 和操作中出了什么问题?

过滤对象数组并动态将属性放入新数组

Chrome是否忽略WebAuthentication userVerification设置?""

如何在Javascript中使用Go和检索本地托管Apache Arrow Flight服务器?

有没有可能使滑动img动画以更快的速度连续?

在服务器上放置了Create Reaction App Build之后的空白页面

你怎么看啦啦队的回应?

WhatsApp Cloud API上载问题:由于MIME类型不正确而导致接收&Quot;INVALID_REQUEST";错误

为什么我的getAsFile()方法返回空?

更新动态数据中对象或数组中的所有值字符串

变量在导入到Vite中的另一个js文件时成为常量.

MarkLogic-earch.suggest不返回任何值

如何利用CSS中的隐藏元素实现平滑扩展和防止网格行间隙

Next.js中的服务器端组件列表筛选

FileReader()不能处理Firefox和GiB文件

如何使用画布在另一个内部绘制一个较小但相同的形状,同时保持恒定的边界厚度?