1

I have this array in my state:

state:{     
   items:[{id:0},{id:1},{id:2},{id:3}]
}

I Am able to do this: I can delete one of these objects, for example, the second one, the array is gonna be like this:

 items:[{id:0},{id:2},{id:3}]

What I want to do (I need help to do it)

I want to iterate over the array and set the id's equally to its own index position in the array, to become this:

 items:[{id:0},{id:1},{id:2}]

So, the objects with Id:2 and Id:3 would be set to Id:1 and Id:2 respectively, according to its new index position.

How can I Achieve it?

I am using the following code in the reducer to delete the desired object:

if(action.type==='deleteItem'){
    return{
        ...state,
        items:[
            ...state.items.slice(0,action.index),
            ...state.items.slice(action.index+1),
        ]

    }
}

How can I implement it to also change the Id properties in each object of the array, according to its new index position?

Thank you all for the attention!

1 Answer 1

2

You can map over the resulting array after you remove one item, like this:

return {
    ...state,
    items: [
        ...state.items.slice(0,action.index),
        ...state.items.slice(action.index + 1),
    ].map((item, index) => ({ ...item, id: index }))
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, it worked perfectly! There is a mistype in your answer though, that second parenthesis after the map argument is not needed. (:
@RogerPeixoto You're right, I typed this without actually running the code haha. I'll edit it just in case anyone stumbles upon this answer in the future. Glad it worked though :)

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.