Spread operator ES6 changing one field in an object in an array

1.5k views Asked by At
case SET_WINE_ITEMS:
  const { index, name, value } = action.payload
  const items = state.items
  items[index][name] = value
  return { ...state, items }

Is there a succinct way to use spread operators to implement the code above?

1

There are 1 answers

0
vedder On

Thank you for your comments. The structure of my array of objects is below, where there can be many objects in the items array.

items: [{
  name: '',
  code: '',
  quantity: '',
  netBottlePrice: '',
  netCasePrice: '',
  caseSize: '',
  volume: '',
  volumeUnit: '',
  amount: ''
}]

I found a way to accomplish updating the redux state without mutating it using spread operators:

case SET_WINE_ITEMS:
  const { index, name, value } = action.payload
  const item = { ...state.items[index], [name]: value }
  const items = [...state.items.slice(0, index), item, ...state.items.slice(index +1) ]
  return { ...state, items }