How to Print All Properties of an Object to JSX in React.js
Let’s see how we can print all properties of an object (interface) to a table in React.js or Next.js.
Suppose we have an object (i.e. map, dictionary, etc), and we want to render each key-value pair as JSX (maybe for testing purposes), but the number of properties are variable.
Our object obj
might contain ten key-value pairs or none.
<table>
<thead>
<tr>
<th>Key</th>
<th>Value</th>
</tr>
</thead>
<tbody>
{
Object.keys(obj).length == 0
? "Object is empty"
: Object.keys(obj).map((key) => {
return (
<tr key={obj[key]}>
<td>{key}</td>
<td><pre>{JSON.stringify(obj[key], null, 2)}</pre></td>
</tr>
)
})
}
</tbody>
</table>
If the object isn’t empty, we can iterate through all the keys with Object::keys
.
If the value is an array, a nested map, or some other object, we’ll use JSON::stringify
to print formatted text.