Search code examples
javascriptreactjsreduxreducers

How to remove a nested array element in Redux Reducer?


been banging my head against this for hours.

I am trying to remove a nested elment of an array in an object. It must be done immutably within a reducer, which is making it tricky.

Here is the object:

questions {
    0:
    answers: [{…}]
    createdAt: "2021-04-28T01:37:21.017Z"
    creator: "607f6ab0ee09c"
    likes: []
    name: "Firstname Lastname"
}

I want to remove just 1 element of the answers array. The problem is I don't know the exact element (of questions) until I search by 'creator' code, and then I can delete the answers element by key #.

I tried using map and filter, but with 3 layers deep that logic just never worked out. I'm also open to using Immutable-js.

thanks so much, quite a baffling issue for what seems like a simple thing to do.

EDIT: I realized I can determine the key of the top level questions object in the action creator and send it over to the reducer. So all I need to know how to do is remove an element of an array in an object, nested in another object.

thanks for any help!


Solution

  • First of clone your questions object by using ... ES6 operator

    const clonedQuestion = {...questions}

    Now for removing element from answers array

    const indexOfElementToRemove = clonedQuestion.answers.findIndex(element => element.creator === clonedQuestion.creator);
    if(indexOfElementToRemove >= 0) {
      clonedQuestion.answers.splice(indexOfElementToRemove, 1)
    }