[英]REACT Delete Element in array of objects
我无法删除对象数组中的元素。 我只想删除数组内的对象。 当我尝试使用.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。
您可以在纯香草ES6中使用滤镜:
var array = todos.filter(item => item.id === 1 || item.id === 3);
由于对象引用不同,所以Array#indexOf
方法始终返回-1
。
您可以使用Array#findIndex
, Array#every
, Object.keys()
和Array#splice
方法。
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)
注意:仅当没有嵌套对象和数组属性值时,以上方法才有效。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.