Categories
Code Snippets React Talking to myself

Turn an array of objects into a table

At work we use a number of javascript files that hold constants we can import to any of our builders or editors. The structure looks something like:

export const importantThing = [
    {
        id: 'slug',
        displayText: 'nice name',
        helpUrl: 'someurl.com/docs/nice-name'
        ...
    },
    ...etc
]

So a fairly large array of objects which makes it easy to work with. With this data structure I needed to export a whole bunch of these objects out and into a table. After a bit of searching there wasn’t anything I could drop in to the tiny project I created to build the tables.

I ended up with two functions that render first the table header and then the table rows:

function renderTableHeader(data) {
  const header = Object.keys(data[0]);
  return header.map((key, index) => <th key={index}>{key}</th>);
}

function renderTableRows(data) {
	const keys = Object.keys(data[0]);
	const table = data.map((row, index) => {
		return (
			<tr key={index}>
				{keys.map((key, index) => <td key={index}>{JSON.stringify(row[key])}</td>)}
			</tr>
		)
	});
	return table;
}

When implemented in the react component:

<table className="table table-sm">
  <tbody>
    <tr>{renderTableHeader(importantThing)}</tr> 
      {renderTableRows(importantThing)}
  </tbody>
</table>

Small and simple without any external libraries or extra bells and whistles. This gives a very plain table that I can easily copy and paste into a spreadsheet, print, or in this case share with another team so they have easy access to all of the underlying data from our production app.