Herm Herm - 1 month ago 17
React JSX Question

Dynamically iterating over an array of json objects in React

I am executing an api call that returns an array of json objects. Here is an example of what I can expect to be returned:

[
{"id": 1, "name": "Pete", "age": 22},
{"id": 2, "name": "Sarah", "age": 32},
{"id": 3, "name": "Marshall", "age": 33}
]


I am trying to loop through this object in order to create table rows, whilst dynamically assigning each key in each json object as an attribute, without having to explicitly state the key. For example, I would like to render this object into the following structure:

<tr key=1>
<td>Pete</td>
<td>22</td>
</tr>
<tr key=2>
<td>Sarah</td>
<td>32</td>
</tr>
<tr key=3>
<td>Marshall</td>
<td>33</td>
</tr>


My legacy code looks like this:

var MyMembers= this.props.Members.map((Member) => {
return (
<tr key={Member.id}>
<td>{Member.name}</td>
<td>{Member.age}</td>
</tr>
)
});


In this piece of legacy code I am however explicitly calling the 'name' and 'age' attributes in order to create 'td' tags. Is there a way that I could loop through each object and create a 'td' value for each key in said object without explicitly calling the key name?

Answer

This should work:

 var MyMembers= this.props.Members.map((Member) => {
  var keys = Object.keys(Member)
  var index = keys.indexOf("id");
  if (index > -1) {
     // removes the "id" element from the keys.
     keys.splice(index, 1);
  }
  var divs = keys.map(k => <td>{Member[k]}</td>)
  return (
   <tr key={Member.id}>
   divs
   </tr>
  )
 });
Comments