I have an array whose data I retrieve via the map()
method. How do I put the key
in the id
of the array record?
Here’s just the code:
const [Arr, setArr] = useState([{ id: null, value: "text" }]);
{Arr.map((item, i) => { ... })}
And I want to put i
from the map()
method into the id
array Arr
.
How do I do it? Thanks!
2
Answers
The simplest way to set
i
toid
inside an array’s element via.map
:I’ve also added improvements in the naming:
Arr
->arr
since most of the time camelCase format is applied to JavaScript code and it’s ecosystem.i
->index
, sincei
usually refers to an imperative for loop styleBut if your array is a dynamic and the data will be removed/changed in-place – having index as id could lead to potential bugs, especially if you will use this index as id for React keys and it will be a dynamic one.
I assume you want to update (mutate) the
id
value in theArr
using index for every item. You can achieve it by usinguseEffect
like this:This will change the
Arr
value when the components is mounted/created. But if you don’t want to mutate theArr
value, you can just use this line: