-1

I have an array of objects and I want to replace one of the objects in an array with a new object for which I have used an array method of indexOf and splice. But it is not working also in the log I found the value I am getting using indexOf is '-1', can anyone please help me.

my state

export const todos = [
  {
    id: "1",
    item: "Buy Milk"
  },
  {
    id: "2",
    item: "Buy Apples"
  },
  {
    id: "3",
    item: "Buy Banana"
  }
];

action.payload

[
  {
    id: "1"
    item: "Buy Milk"
  },
  {
    id: "1"
    item: "Do exercise"
  }
];

My code

case UPDATE_TODO:
      newTodos = [...state];
      console.log(action.payload[0]);   //{id: "1",item: "Buy Milk"} 
      let getIndex = newTodos.indexOf(action.payload[0]);
      console.log(getIndex);             // getting -1 instead of 0
      newTodos.splice(getIndex, 1, action.payload[1]);
      return newTodos;
Siddhesh
  • 73
  • 1
  • 7
  • 2
    Does this answer your question? [Find object by id in an array of JavaScript objects](https://stackoverflow.com/questions/7364150/find-object-by-id-in-an-array-of-javascript-objects) – E_net4 Jan 09 '21 at 13:29
  • 1
    `indexOf` won't work as expected with object values. Use `find` to check against the `id` attribute. – E_net4 Jan 09 '21 at 13:31
  • @E_net4ano-commentdownvoter if the action.payload posted is accurate, a `find` for just `id` will not work, because there are two `id: 1`, but `find`will be the way to go – novarx Jan 09 '21 at 13:37

2 Answers2

1

The comparison of arrays can not use indexOf directly, because they are not base value type.

You can try:

case UPDATE_TODO:
      newTodos = [...state];
      console.log(action.payload[0]);   //{id: "1",item: "Buy Milk"} 
      let getIndex = newTodos.findIndex(item => item.id === action.payload[0].id);
      console.log(getIndex);             // get 0
      newTodos.splice(getIndex, 1, action.payload[1]);
      return newTodos;
Chuion Mr
  • 36
  • 3
0

The Array function indexOf() searches the array for a Object equal to the searched one. It checks equality by ===(see: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf).

So since i.e. {a: 1} === {a: 1} will return false your search with indexOf will not work.

novarx
  • 498
  • 3
  • 6