Home > Enterprise >  Javascript render object of arrays as table
Javascript render object of arrays as table

Time:07-21

I have a JavaScript object in which I am trying to render as a table, though I am unable to figure out how to access each individual array.

Here is a sample of the object (defLogTable):

{
    "headings": [
        "Item",
        "Equip Tag",
        "Ref#",
        "Description",
        "Corrective Action Taken or Date Completed"
    ],
    "values": [
        [
            1,
            "RTU-1",
            1,
            "This did not work",
            "Make it Work"
        ],
        [
            2,
            "EF-1",
            2,
            "This also didn't work",
            "Make this one work too"
        ]
    ]
}

Each 'values' array corresponds to a row in the table.

And What I have tried:

<table className="def-tbl">
                    <tbody>
                        {console.log(defLogTable)}
                        {defLogTable.headings.map(heading => (
                            <th>{heading}</th>
                        ))}
                    </tbody>
                </table>

Error: TypeError: Cannot read properties of undefined (reading 'headings')

Any help is appreciated!!

CodePudding user response:

Use a nested map to render each row in the values property.

<table className="def-tbl">
  <thead>
    <tr>
      {defLogTable.headings.map(heading => (
        <th>{heading}</th>
      ))}
    </tr>
  </thead>

  <tbody>
    {defLogTable.values.map(row => (
      <tr>
        {row.map(cell => (
          <td>{cell}</td>
        ))}
      </tr>
    ))}
  </tbody>
</table>
  • Related