0

I need to map through two different arrays adding them as rows to a single table. To do this I am attempting to use a counter instead of index (since react requires a unique key per iteration). I can't use index for the key because I have to concatenate and that makes the indexes not unique per row. So instead, I am attempting with a counter but am getting stuck on how I should increment the number...

...
    {dateTable.categories.map((category, indexThree, categories) =>
      {
        let rowCounter = 0;
        const firstRows = category.firstRows.map((row, indexFour, firstRowsArr) =>
          <tr key={indexFour}>
            {indexFour === 0 ?
            <td>
                <h5>{category.name}</h5>
            </td> : <td />
            }
            <td>{row.valOne}</td>
            <td style={{backgroundColor: "#ffedbc"}}>{row.valTwo}</td>
            <td>{row.valThree}</td>
            <td>{row.valFour}</td>
          </tr>
        );
        const secondRows = category.secondRows.map((row, indexFive, secondRowsArr) =>
        <tr key={indexFive+rowCounter}>
          {indexFive === 0 && category.firstRows.length === 0 ?
          <td>
              <h5>{category.name}</h5>
          </td> : <td />
          }
          <td>{row.valOne}</td>
          <td>{row.valTwo}</td>
          <td>{row.valThree}</td>
          <td>{row.valFour}</td>
        </tr>
        );
        console.log("rowCounter", rowCounter);
        return firstRows.concat(secondRows);
      }
    )}
...
1
  • The key is a string. You can just use both indices joined with a separator. Or you can create a single flat array first and then map over that single array. Commented Sep 22, 2020 at 16:55

2 Answers 2

1

You could just use

<tr key={rowCounter++}>

for both.


But if you are not going to use this for an arbitrary number of categories, you should just drop the counter and prepend a different string for each array, along with its index.

<tr key={`first-${indexFour}`}>

and

<tr key={`second-${indexFive}`}>

But the best would be if you had a unique key for reach row, so you could do

<tr key={row.someUniqueKey}>
Sign up to request clarification or add additional context in comments.

1 Comment

Thx, this actually answers the question.
1

you can add the firstArray length on the secondArray index, without counter

<tr key={indexFive + firstRows.length}>

1 Comment

This works perfectly. I should have thought of that, but probably just need rest. Thanks so much!!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.