TariqN TariqN - 2 months ago 14
Javascript Question

How can i properly clone json array in redux?

Im new in Redux and Redux concepts look weird for me at first. Let say i have an array in redux state.

const state = [
{show: false, id : '1'},
{show: false, id : '2'},
{show: false, id : '3'},
{show: false, id : '4'},
{show: false, id : '5'}
]


I want to clone this array and change/mutate one object.

I tried something like this in reducer but it did not work.

return [...state.concat(Object.assign({}, state[0], {show:true} )).slice(1,5)];


Any help or explanation would be nice.

Answer

I think you might have switched [] with {} in your question.

Assuming your state is:

const state = [ 
  { show: false, id: '1' },
  { show: false, id: '2' },
  { show: false, id: '3' },
  { show: false, id: '4' },
  { show: false, id: '5' }
]

You can write a reducer like this:

return [
  ...state.slice(0, index),
  Object.assign({}, state[index], { /* your changes */ })
  ...state.slice(index + 1)
]

Where index is the index of the element you want to change.

References