0

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

2
  • Are you using some kind of JavaScript framework here? If not, none of this will work (you can't put curly braces in ordinary HTML and have anything magical happen). Commented Jul 20, 2022 at 19:36
  • 1
    This is React JSX, syntax-wise everything is okay Commented Jul 20, 2022 at 19:39

1 Answer 1

1

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>
Sign up to request clarification or add additional context in comments.

3 Comments

This is what I currently have, I receive the error TypeError: Cannot read properties of undefined (reading 'headings')
So your defLogTable value is undefined. Probably because the initial state of defLogTable is not the object that you show in your question, but undefined. Just check if defLogTable is undefined before rendering the table.
I never thought that would be the case since I was able to console.log() it, but adding a simple 'defLogTable &&' worked like a charm, thank you sir

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.