skip to Main Content

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


  1. The simplest way to set i to id inside an array’s element via .map:

    const [arr, setArr] = useState([{ id: null, value: "text" }]);
    
    {arr.map((item, index) => { ..., id: index })}
    

    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, since i usually refers to an imperative for loop style

    But 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.

    Login or Signup to reply.
  2. I assume you want to update (mutate) the id value in the Arr using index for every item. You can achieve it by using useEffect like this:

    useEffect(() => {
      setArr(Arr.map((item, i) => ({ ...item, id: i})));
    }, [])
    

    This will change the Arr value when the components is mounted/created. But if you don’t want to mutate the Arr value, you can just use this line:

    Arr.map((item, i) => ({ ...item, id: i}))
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search