将每个数组索引渲染为React中的每个表

时间:2019-12-17 09:48:53

标签: reactjs

我有这样的数据。

products: [
  {b: "brand1", N: "N1", M: "M1", B: "B1", S: "y1", O: "y1", A: "y1", D: "y1"},
  {b: "brand2", N: "N2", M: "M2", B: "B2", S: "y2", O: "y2", A: "y2", D: "y2"},
  {b: "brand3", N: "N3", M: "M3", B: "B3", S: "y3", O: "y3", A: "y3", D: "y3"},
  {b: "brand4", N: "N4", M: "M4", B: "B4", S: "y4", O: "y4", A: "y4", D: "y4"},
  ]

我需要在每个表中显示产品数组的每个索引。

我已经尝试过了,但是它在单个表中显示所有数组索引

Products.map(row => (
             <tr key={ row.key } >
              <td >{ row.key }</td>
              { productid.map(product => (
                  <td key={ product }>{ row[product].toString() }</td>
              ))}
          </tr>
      ))

1 个答案:

答案 0 :(得分:0)

我认为这会起作用。

products.map((row, index) => (
  <table key={index}>
  <tr>
    <th>
      {Object.keys(row).map(item => (
        <td>{item}</td>
      ))}
    </th>
  </tr>
  <tr>
    <td>
      {Object.keys(row).map(item => (
        <td>{row[item]}</td>
      ))}
    </td>
  </tr>
</table>

));

您还可以参考我为此创建的代码和框。https://codesandbox.io/s/react-example-6uljz