0

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;

3 Answers 3

3

An option is to use array filter:

state = [ { ... }, ... ] // Your array
state = state.filter(item => !(item.name === action.value && item.completed === false));
Sign up to request clarification or add additional context in comments.

2 Comments

Doesn't this leave state with just that object tho? Don't you want item.name !== action.name etc?
It will also delete repeated items. This would be a good solution if the objects has a unique id or something like that.
1

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

Comments

0

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.