You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过循环从嵌套JSON提取值并在HTML表格中展示

没问题,我来帮你把这段嵌套JSON里的数据提取出来,整理成清晰的HTML表格。先给你看最终的表格效果,再附上动态处理的代码示例:

提取后的HTML表格

<table border="1">
  <thead>
    <tr>
      <th>ID</th>
      <th>Title</th>
      <th>Business Subject Areas</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>3</td>
      <td>Doing Business In...</td>
      <td>
        Market and Sell Products/Service<br>
        Deliver Products/Services<br>
        HR<br>
        Legal<br>
        Finance<br>
        Tax<br>
        Treasury<br>
        IT
      </td>
    </tr>
  </tbody>
</table>

动态提取并生成表格的JavaScript示例

如果需要批量处理这类JSON数据,或者要在网页中动态生成表格,可以用下面的代码逻辑(注:原始JSON里的attachm...我补全为attachments: [],避免代码运行时出现未定义字段的错误):

// 你的原始JSON数据(补全截断字段)
const jsonData = [
  {
    "id": "3",
    "title": "Doing Business In...",
    "businessSubjectAreas": [
      { "businessSubjectArea": "Market and Sell Products/Service" },
      { "businessSubjectArea": "Deliver Products/Services" },
      { "businessSubjectArea": "HR" },
      { "businessSubjectArea": "Legal" },
      { "businessSubjectArea": "Finance" },
      { "businessSubjectArea": "Tax" },
      { "businessSubjectArea": "Treasury" },
      { "businessSubjectArea": "IT" }
    ],
    "attachments": []
  }
];

// 生成HTML表格的函数
function generateBusinessTable(data) {
  // 创建表格元素
  const table = document.createElement('table');
  table.border = "1";
  
  // 构建表头
  const headerRow = document.createElement('tr');
  ["ID", "Title", "Business Subject Areas"].forEach(headerText => {
    const th = document.createElement('th');
    th.textContent = headerText;
    headerRow.appendChild(th);
  });
  table.appendChild(headerRow);
  
  // 构建表体内容
  data.forEach(item => {
    const row = document.createElement('tr');
    
    // 填充ID列
    const idCell = document.createElement('td');
    idCell.textContent = item.id;
    row.appendChild(idCell);
    
    // 填充Title列
    const titleCell = document.createElement('td');
    titleCell.textContent = item.title;
    row.appendChild(titleCell);
    
    // 填充业务领域列,将数组转为换行分隔的文本
    const areasCell = document.createElement('td');
    const areasList = item.businessSubjectAreas.map(area => area.businessSubjectArea).join('<br>');
    areasCell.innerHTML = areasList;
    row.appendChild(areasCell);
    
    table.appendChild(row);
  });
  
  return table;
}

// 将生成的表格添加到页面中
document.body.appendChild(generateBusinessTable(jsonData));

这段代码会遍历JSON数组,自动提取每个条目的id、title,以及businessSubjectAreas数组里的所有业务领域,最终生成带边框的HTML表格,业务领域用换行符分隔显示,可读性很强。

内容的提问来源于stack exchange,提问作者vamsi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:11:38