obeliksz obeliksz - 3 years ago 106
Javascript Question

Get number of current element in parent array object

I have the following JSON object and when in building the Message.jsx I would like to include as id the number of the current message element in the section array. How could I do that?

{ "sections": [
{
"message": {
"from": "someone",
"body": "ibsum"
}
},
{
"message": {
"from": "someone else",
"body": "lorem"
}
}, ... ] }


Can I actually do this without explicitly setting an id property for each object in section array?

Answer Source

Use the second property of map which is the element index within the array. You can set the key in the same way. Remember, indexes start from 0.

So something like this:

<Section>
{this.props.messages.map((message, i) => {
  return <Message key={i} id={i} info={message} />
})}
</Section>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download