0

I want to update an item of an array at a given index in my reducer using ES6 spread operator ... Here is what I am doing

let array = action.payload.items;
return [...array, array[3].id:555]

By this way editing works very well, but it also adds an extra item in the array.

Any help???

h_h
  • 1,201
  • 4
  • 28
  • 47

2 Answers2

0

Use to index to get the item, clone it and change the id with Object#assign. Create the new array by using Array#slice and spread to insert the updated item to the right place in the new array:

const items = [{ id: 1 }, { id: 2 }, { id: 3 }]; // action.payload.items

const index = 1;

const itemToUpdate = Object.assign({}, items[index], { id: 1000});

const result = [...items.slice(0, index), itemToUpdate, ...items.slice(index + 1)]; // return ...

console.log(result);
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
  • I updated my question, it can be any array index which I want to edit, not exactly first – h_h Dec 07 '17 at 20:45
0

Please consider this answer over here : https://stackoverflow.com/a/34582848/51428

This is easily applicable to your question,by inserting your new object at the index where yiu are removing the element.

Consider keeping your old element intact, whereby you can also use spreading to create the new element

const itemToUpdate = {...items[index], id: 1000}
flq
  • 22,247
  • 8
  • 55
  • 77