我在删除对象数组中的元素时遇到问题。我想简单地删除数组中的对象。当我尝试使用.IndexOf()时。它让我回来-1。有没有办法在不创建对每个对象的引用的情况下执行此操作。
这是我的对象数组。
let todos = [{
id: 1,
task: 'Finish This React App'
},{
id: 2,
task: 'Do Another App'
},{
id: 3,
task: 'Pass data from the parent to the child and reverse'
}]
let task = {id:2,task:'Do Another App'}
let todosArray = this.props.todos
todosArray.indexOf(task,0) //= -1
总的来说,我想在todos数组中只有对象1和3。
答案 0 :(得分:4)
您可以在纯vanillia ES6中使用过滤器:
var array = todos.filter(item => item.id === 1 || item.id === 3);
答案 1 :(得分:1)
Array#indexOf
方法始终返回-1
,因为对象引用不一样。
您可以使用 Array#findIndex
, Array#every
, Object.keys()
和 {{ 3}} 方法。
let todos = [{
id: 1,
task: 'Finish This React App'
}, {
id: 2,
task: 'Do Another App'
}, {
id: 3,
task: 'Pass data from the parent to the child and reverse'
}]
let task = {
id: 2,
task: 'Do Another App'
};
let keys = Object.keys(task);
// remove element from the array by index
todos.splice(
// get the index of the element
todos.findIndex(function(obj) {
// check all property values are equal
return keys.every(function(k) {
return task[k] === obj[k];
});
// if you want to check only the `id` property then // you can avoid the above codes and use
// return obj.id === task.id;
}), 1);
console.log(todos)
注意:只有没有嵌套对象和数组属性值时,上述方法才有效。