Murali
Murali

Reputation: 378

How to delete an Object in an array in ES6

Json Object:-

{
  "todos": [
    {
      "name": "New Todo",
      "completed": false
    },
    {
      "name": "Second Todo",
      "completed": false
    },
    {
      "name": "Third Todo",
      "completed": false
    },
    {
      "name": "Fourth Todo",
      "completed": false
    }
  ]
}

In My json object I want to remove particular object. I have tried with the below code but it is not removing.

const obj1 = {name: action.value, completed: false};
           const index = state.indexOf(obj1);

                if (index !== -1) {
                    state.splice(index, 1);
                }

            return [...state,state]; 
            break;

Upvotes: 0

Views: 443

Answers (3)

Faly
Faly

Reputation: 13356

An option is to use array filter:

state = [ { ... }, ... ] // Your array
state = state.filter(item => !(item.name === action.value && item.completed === false));

Upvotes: 3

Mauro Aguilar
Mauro Aguilar

Reputation: 1338

In order to make that work you'll need to keep the reference of the object you want to delete:

state = {
  "todos": [
    {
      "name": "New Todo",
      "completed": false
    },
    {
      "name": "Second Todo",
      "completed": false
    },
    {
      "name": "Third Todo",
      "completed": false
    },
    {
      "name": "Fourth Todo",
      "completed": false
    }
  ]
};


item = state.todos[2];

// Delete:
index = state.todos.indexOf(item);

state = {
  todos: [
    ...state.todos.slice(0, index),
    ...state.todos.slice(index + 1)
  ]
};

console.log(state)

Upvotes: 0

Suren Srapyan
Suren Srapyan

Reputation: 68655

Your const obj will never be found in the state array, because the indexOf will check each item based on the reference. As you create your obj which has different reference and is not included in the array, it will never be found there.

If you want to compare each item based on two conditions, you can use filter function and do the reverse actions to get the filtered list.

const items = [
    {
      "name": "New Todo",
      "completed": false
    },
    {
      "name": "Second Todo",
      "completed": false
    },
    {
      "name": "Third Todo",
      "completed": false
    },
    {
      "name": "Fourth Todo",
      "completed": false
    }];
    
const obj = { name: 'New Todo', completed: false };

const newArr = items.filter(item => item.name !== obj.name || item.completed !== obj.completed);

console.log(newArr);

Upvotes: 1

Related Questions