在 html 表格中显示对象数组

问题描述 投票:0回答:1

我有以下对象数组,如下

const initState = [
    { id: 1, name: "bread", quantitiy: 50 },
    { id: 2, name: "milk", quantitiy: 20 },
    { id: 3, name: "water", quantitiy: 10 }
  ];

下面是上述

initState
输入中预期的通用 html 数据。

enter image description here

所以为了实现这个表,我在反应组件中以这种方式编写了代码。 (注意,为了简单起见,我只是在此处显示 jsx)

return (
    <table>
      <tr key={"header"}>
        {Object.keys(state[0]).map((key) => (
          <th>{key}</th>
        ))}
      </tr>
      {state.map((item) => (
        <tr key={item.id}>
          {Object.values(item).map((val) => (
            <td>{val}</td>
          ))}
        </tr>
      ))}
    </table>
    )

这绝对没问题。我陷入了表头名称反转的情况。例如如下所示。请忽略 css 宽度不匹配的问题。

enter image description here

基本上,第一行的 id、名称、数量现在位于第一列,并且所有数据显示也都反转了。我尝试在网上查找是否有任何与以这种方式显示数据相关的内容,但我所能找到的只是我上面实现的。

有人可以阐明/深入了解如何在此表中显示数据吗?我应该以某种方式调整

initialstate
变量,还是应该更改 jsx 以与上面实现的显示不同。如有任何帮助,我们将不胜感激。

javascript html reactjs arrays json
1个回答
0
投票

我不知道 React 以及可用的在线游乐场如何工作,无法为您提供直接的 React 解决方案,但基本上,您只需要这样做:

首先循环第一个对象的键,因为对于每个对象,您都必须创建一个表row

然后在该循环中,将当前密钥插入第一个单元格中。

然后循环所有状态对象,并输出当前键的值,以填充该行的其余单元格。

const state = [
    { id: 1, name: "bread", quantitiy: 50 },
    { id: 2, name: "milk", quantitiy: 20 },
    { id: 3, name: "water", quantitiy: 10 }
  ];
  
let html = '<table>';

Object.keys(state[0]).map((key) => {
    html += '<tr>';
    html += '<td>'+key+'</td>';
    state.map((item) => {
        html += '<td>'+item[key]+'</td>';
    });
    html += '</tr>';
});
html += '</table>';

document.body.innerHTML = html;

我假设将其转换为必要的react/jsx语法,对于熟悉该语法的人来说不应该是太大的挑战。

© www.soinside.com 2019 - 2024. All rights reserved.