1

I have following object

state = {"line": [
   {"media": [1, 2, 3 ]},
   {"media": []},
   {"media": []},
]}

What I need is to remove element in media array.

I try the following

return {
            ...state, line: [{
                ...state.line[line_index], media = [
                        ...state.line[line_index].media.slice(0, action.payload.index),
                        ...state.line[line_index].media.slice(action.payload.index + 1)
                ]
            }]
        }

but it doesn't work, it replaces media with object.

I don't get how to do it correctly. Can some one please show the way and describe it please

4
  • Shouldn’t that be media: instead of media =? Commented Apr 27, 2018 at 5:39
  • no, this way it removes all objects besides modified one Commented Apr 27, 2018 at 5:42
  • what do you want to achieve? what is your actions payload looking like? Commented Apr 27, 2018 at 5:44
  • What I need is to remove element in media array. Commented Apr 27, 2018 at 5:45

1 Answer 1

5

What you forgot is reassembling the line array properly. Try breaking it down like this:

const changedElement = {
    ...state.line[lineIndex],
    media: [
        ...state.line[lineIndex].media.slice(0, action.payload.index),
        ...state.line[line_index].media.slice(action.payload.index + 1)
    ]
}

return {
    ...state,
    line: [
        ...state.line.slice(0, line_index),
        changedElement,
        ...state.line.slice(line_index + 1)
    ]
}

What you want to do is write the current structure of your state:

state = {
    line: [
        {
            media: []
        },
        {
            media: []
        }
    ]
}

What you can then do is making it generic and containing state. So, state should be a copy of state (by putting ...state in it) and line should be a copy of line. The only difference between line and state is that it's an array. Making an immutable copy of an array is a bit more involved than making such a copy of an object. But in your code, you did this already for your changedElement.

For a further read on this, you should have a look at immutable update patterns, as these are just recipes you can always reuse: https://redux.js.org/recipes/structuring-reducers/immutable-update-patterns

Sign up to request clarification or add additional context in comments.

1 Comment

that works great, thank you very much. can you please be so kind and describe step by step, because for me it is pain each time when I have to deal with nested arrays and spread op.

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.