Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make key value of map function increment for each element in JavaScript

I am mapping out each field in an array of fields so that each field has an id starting at 1... n number of fields.

I use this as I store all field values in an array, and when a field is changed, I would like data[index] to be updated accordingly.

Here is my code for the map function

{this.state.fields.map((field) => {
return (
    <IssueInputRow
        labelText={field.name}
        key={i}   //want this to increment by 1 for each field, starting a 0                 
        handler={this.handler}
    />
    );
})}

I would like the key for each field to increase by 1 starting at 0. So if there are 3 fields, the keys should be 0,1,2 for the respective fields.

Please let me know how this is possibke

like image 839
Pranav Avatar asked Dec 02 '22 10:12

Pranav


1 Answers

The second argument given to the function given to map is the array index, so you could use that.

{this.state.fields.map((field, i) => {
  return (
    <IssueInputRow
      labelText={field.name}
      key={i}             
      handler={this.handler}
    />
  );
})}
like image 120
Tholle Avatar answered Dec 04 '22 23:12

Tholle