Reputation: 1772
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?
Upvotes: 0
Views: 2267
Reputation: 1084
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>
)
});
Upvotes: 1
Reputation: 888
If you want to do it in a functional way you could use this:
var list = this.state.data.map(p => {
return (
<tr key={p.id}>
{Object.keys(p).filter(k => k !== 'id').map(k => {
return (<td key={p.id + '' + k}>{p[k]}</td>);
})}
</tr>
);
})
Or for reading comprehension split the items out of the final return:
var list = this.state.data.map(p => {
var items = Object.keys(p)
.filter(k => k !== 'id')
.map(k => {
return (
<td key={p.id + k}>{p[k]}</td>
)
});
return (
<tr key={p.id}>
{items}
</tr>
);
});
Upvotes: 1