如何在ES6中删除数组中的Object

时间:2017-09-04 13:51:43

标签: javascript ecmascript-6

Json对象: -

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

在我的json对象中,我想删除特定对象。我尝试使用下面的代码,但它没有删除。

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

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

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

3 个答案:

答案 0 :(得分:3)

选项是使用数组过滤器:

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

答案 1 :(得分:1)

const obj阵列中永远找不到您的state,因为indexOf会根据参考检查每个项目。当您创建具有不同引用但未包含在数组中的obj时,将永远不会在那里找到它。

如果您想根据两个条件比较每个项目,可以使用filter函数并执行相反的操作以获取已过滤的列表。



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




答案 2 :(得分:0)

为了完成这项工作,您需要保留要删除的对象的引用:



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)