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

如何用JavaScript从含嵌套对象的多维数组生成HTML表格?

我明白你要做的是把不同产品的specs属性整理成横向对比的表格,键在第一列,每个产品对应的值在后续列,没有对应键的产品显示--对吧?咱们来一步步调整代码实现这个需求:

核心思路

  • 先从所有产品的specs里收集所有唯一的属性键,确保第一列能覆盖所有可能的属性
  • 针对每个属性键生成一行:第一列是键名,然后依次遍历每个产品,取出对应的值,没有的就填--
  • 修正表头的插入顺序,避免产品顺序颠倒

修改后的完整代码

<table class="responsive-table">
 <thead>
 <tr class="js-th"></tr>
 </thead>
 <tbody class="js-tb"></tbody>
</table>

<script>
const tableHead = document.querySelector('.responsive-table .js-th');
const tableBody = document.querySelector('.responsive-table .js-tb');
const getData = [
 [{ title: 'title1', image: 'https://placehold.it/25x25', price: '$55.55', specs: { weight: '40lbs', color: 'yellow', available: true } }],
 [{ title: 'title2', image: 'https://placehold.it/25x25', price: '$55.55', specs: { color: 'red', available: false } }],
 [{ title: 'title3', image: 'https://placehold.it/25x25', price: '$55.55', specs: { available: true } }]
];

buildTable();

function buildTable() {
  // 1. 构建表头:先添加"specs"列,再逐个追加产品信息列
  tableHead.insertAdjacentHTML('beforeend', '<th>specs</th>');
  getData.forEach(productGroup => {
    const product = productGroup[0];
    const headHtml = `
      <th>
        <img src="${product.image}" />
        <p>${product.title}</p>
        <p>${product.price}</p>
      </th>
    `;
    tableHead.insertAdjacentHTML('beforeend', headHtml);
  });

  // 2. 收集所有specs的唯一键(自动去重)
  const allSpecKeys = new Set();
  getData.forEach(productGroup => {
    const specs = productGroup[0].specs;
    Object.keys(specs).forEach(key => allSpecKeys.add(key));
  });
  const specKeysArray = Array.from(allSpecKeys);

  // 3. 构建表格主体行
  let rows = '';
  specKeysArray.forEach(key => {
    let rowHtml = `<tr><td>${key}</td>`;
    // 遍历每个产品,匹配对应属性值,无则显示--
    getData.forEach(productGroup => {
      const product = productGroup[0];
      const value = product.specs[key] !== undefined ? product.specs[key] : '--';
      rowHtml += `<td>${value}</td>`;
    });
    rowHtml += '</tr>';
    rows += rowHtml;
  });

  tableBody.insertAdjacentHTML('beforeend', rows);
}
</script>

关键步骤解释

  1. 表头顺序修正:原来用afterbegin会让先插入的产品列排在最前面,导致顺序颠倒,改成beforeend就能按getData的原始顺序追加产品列。
  2. 收集唯一属性键:用Set自动去重,确保每个属性只在第一列出现一次,不管哪个产品有没有这个属性。
  3. 动态生成对比行:遍历每个属性键,逐个检查每个产品是否包含该属性,缺失的属性统一填充--,完美实现横向对比的效果。

运行这段代码后,你就能得到符合需求的表格:第一列是所有specs的键,后续每列对应一个产品的属性值,缺失属性显示--。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 12:42:33