简体   繁体   中英

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;

An option is to use array filter:

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

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); 

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) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM