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

JavaScript如何遍历嵌套对象并将属性值插入HTML表格单元格

解决方案

你遇到的核心问题有两个:

  1. 原内层循环固定读取members[i].name,导致所有单元格都填充了名字
  2. 你尝试的members[i].obj[x]写法有误,JS 支持通过对象[属性名]的方式动态读取属性,不需要额外的obj中间层

另外需要注意:你代码中的i、x变量没有声明作用域,会默认成为全局变量,容易引发不可预期的问题;同时insertCell(0)每次向行首插入单元格,会导致最终列顺序和预期相反。

你可以直接用以下实现:

1. 前置HTML表格结构

<table id="heroTable" border="1">
  <thead>
    <tr>
      <th>姓名</th>
      <th>年龄</th>
      <th>真实身份</th>
      <th>超能力</th>
    </tr>
  </thead>
  <tbody></tbody>
</table>

2. JS渲染逻辑

const data = [
  {
    squadName: 'Super Hero Squad',
    homeTown: 'Metro City',
    formed: 2016,
    secretBase: 'Super tower',
    active: true,
    members: [
      {
        name: 'Molecule Man',
        age: 29,
        secretIdentity: 'Dan Jukes',
        powers: ['Radiation resistance', 'Turning tiny', 'Radiation blast']
      },
      {
        name: 'Madame Uppercut',
        age: 39,
        secretIdentity: 'Jane Wilson',
        powers: ['Million tonne punch', 'Damage resistance', 'Superhuman reflexes']
      },
      // 第三个超级英雄按相同结构补充即可
    ]
  }
]

// 定义要渲染的属性顺序,和表格列一一对应
const displayColumns = ['name', 'age', 'secretIdentity', 'powers'];
const members = data[0].members;

function renderHeroTable(tableId) {
  const tableRef = document.getElementById(tableId);
  // 遍历所有超级英雄,每行对应一个英雄
  members.forEach(hero => {
    const newRow = tableRef.insertRow(-1);
    // 遍历要显示的属性,每列对应一个属性
    displayColumns.forEach((colKey, index) => {
      const newCell = newRow.insertCell(index);
      // 处理超能力为数组的情况,转成顿号分隔的字符串
      const cellContent = Array.isArray(hero[colKey]) 
        ? hero[colKey].join('、') 
        : hero[colKey];
      newCell.appendChild(document.createTextNode(cellContent));
    })
  })
}

// 调用渲染方法,传入对应表格ID
renderHeroTable('heroTable');

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 15:45:03