Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Javascript render object of arrays as table

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!!

>Solution :

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading