admin管理员组文章数量:1401650
I am having trouble deleting an element inside an array of objects. I want to simply delete an object inside the array. When I try to use .IndexOf(). It gives me back -1. is there a way to do this without creating a reference to each object.
This is my Array of objects.
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
Overall I want to only have objects 1 and 3 inside the todos array.
I am having trouble deleting an element inside an array of objects. I want to simply delete an object inside the array. When I try to use .IndexOf(). It gives me back -1. is there a way to do this without creating a reference to each object.
This is my Array of objects.
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
Overall I want to only have objects 1 and 3 inside the todos array.
Share Improve this question asked Aug 22, 2016 at 19:31 BrianBrian 1111 gold badge4 silver badges13 bronze badges 2- This isn't a react question. – ray Commented Aug 22, 2016 at 19:41
- @brian-bier didn't specify this, but in react you should never modify the original value when changing state. I believe his question is about achieving this. Not just about removing from an array – user1372408 Commented Feb 1, 2018 at 15:20
2 Answers
Reset to default 6You can use filter in pure vanillia ES6 :
var array = todos.filter(item => item.id === 1 || item.id === 3);
The Array#indexOf
method always returns -1
since the objects reference is not the same.
You can use Array#findIndex
, Array#every
, Object.keys()
and Array#splice
methods.
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)
Note : Above methods only works if there is no nested object and array property value.
本文标签: javascriptREACT Delete Element in array of objectsStack Overflow
版权声明:本文标题:javascript - REACT Delete Element in array of objects - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744311679a2600060.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论