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

在Angular 6/TypeScript中如何从JSON对象获取键名?

没问题,这事儿其实挺简单的!核心就是用JavaScript的Object.keys()方法提取JSON对象的键名,然后动态生成表格的表头和内容。我给你拆解下具体实现思路和代码示例:

核心思路

因为JSONPlaceholder返回的同类型数据结构都是一致的,所以我们只需要取数组中第一个对象的所有键,就能得到完整的表头字段列表。之后再遍历数据,把每个对象的对应值填入表格即可。

完整代码示例(原生JavaScript)

假设你已经通过fetch或者其他方式拿到了JSON数据,我们可以这样实现:

// 模拟从JSONPlaceholder获取到的数据
const posts = [{ 
  userId: 1, 
  id: 1, 
  title: "sunt aut facere repellat provident occaecati excepturi optio reprehenderit", 
  body: "quia et suscipit suscipit recusandae consequuntur expedita et cum reprehenderit molestiae ut ut quas totam nostrum rerum est autem sunt rem eveniet architecto" 
}];

// 先判断数据是否为空,避免报错
if (!posts.length) {
  console.log('暂无数据可展示');
  return;
}

// 提取表头字段:获取第一个对象的所有键名
const headerKeys = Object.keys(posts[0]);

// 获取页面上的容器(比如你想把表格放到id为"table-wrap"的div里)
const tableContainer = document.getElementById('table-wrap');

// 创建表格元素
const table = document.createElement('table');
// 可以加个基础样式,实际项目建议用CSS控制
table.style.borderCollapse = 'collapse';
table.style.width = '100%';

// 生成表头部分
const thead = document.createElement('thead');
const headerRow = document.createElement('tr');

headerKeys.forEach(key => {
  const th = document.createElement('th');
  // 把键名首字母大写,让表头更美观
  th.textContent = key.charAt(0).toUpperCase() + key.slice(1);
  th.style.border = '1px solid #ddd';
  th.style.padding = '8px';
  th.style.backgroundColor = '#f5f5f5';
  headerRow.appendChild(th);
});
thead.appendChild(headerRow);
table.appendChild(thead);

// 生成表格内容部分
const tbody = document.createElement('tbody');

posts.forEach(item => {
  const row = document.createElement('tr');
  // 按照表头的顺序,依次填充每个单元格的内容
  headerKeys.forEach(key => {
    const td = document.createElement('td');
    td.textContent = item[key];
    td.style.border = '1px solid #ddd';
    td.style.padding = '8px';
    row.appendChild(td);
  });
  tbody.appendChild(row);
});
table.appendChild(tbody);

// 把表格添加到页面容器中
tableContainer.appendChild(table);

关键细节说明

  1. Object.keys()的作用:这个方法会返回一个包含对象所有可枚举键名的数组,完美适配我们提取表头的需求。
  2. 数据空值判断:先检查数组长度,避免当数据为空时,posts[0]报错的情况。
  3. 表头美化:把键名首字母大写,让表头看起来更专业,当然你也可以根据需求自定义表头文本(比如把userId改成"用户ID")。
  4. 样式控制:示例里用了行内样式,实际项目中建议用外部CSS来统一控制表格样式,更易维护。

如果你用框架(比如React)

思路是一样的,只是渲染方式换成框架的语法:

function PostTable({ posts }) {
  if (!posts.length) return <p>暂无数据</p>;
  
  const headerKeys = Object.keys(posts[0]);
  
  return (
    <table style={{ borderCollapse: 'collapse', width: '100%' }}>
      <thead>
        <tr>
          {headerKeys.map(key => (
            <th key={key} style={{ border: '1px solid #ddd', padding: '8px', backgroundColor: '#f5f5f5' }}>
              {key.charAt(0).toUpperCase() + key.slice(1)}
            </th>
          ))}
        </tr>
      </thead>
      <tbody>
        {posts.map(item => (
          <tr key={item.id}>
            {headerKeys.map(key => (
              <td key={key} style={{ border: '1px solid #ddd', padding: '8px' }}>
                {item[key]}
              </td>
            ))}
          </tr>
        ))}
      </tbody>
    </table>
  );
}

这样不管是原生JS还是框架,都能轻松实现动态表头的表格啦!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 07:09:43