Reputation: 324
I have an array of objects that is something like this one in my react state:
timers:
{
id:"-LL-YVYNC_BGirSn1Ydu"
title: "Project Title"
project: "Project Name",
elapsed: 0,
runningSince: 0,
},
{
id:"-LL-YVYNC_BGirSn1Ydu-2",
title: "Project Title 2"
project: "Project Name",
elapsed: 0,
runningSince: 0,
},
{
id:"-LL-YVYNC_BGirSn1Ydu-3",
title: "Project Title 3"
project: "Project Name 2",
elapsed: 0,
runningSince: 0,
}
Sometimes i need to bulk delete "timers" with the same "project" and update the state without them. I have an array like:
items=["-LL-YVYNC_BGirSn1Ydu", "-LL-YVYNC_BGirSn1Ydu-2"]
containing the id's of the items I need to remove. I am using this method to achieve the result:
handleDeleteProject = (projectId)=>{
//Creates the array with the id of removing elements
let rObject = this.findTimers(projectId);
for (const key of Object.keys(rObject)){
tObject=[...this.state.timers];
tObject = tObject.filter(timer=>timer.id !== rObject[key]);
this.setState({
timers: tObject
})
}
}
The problem is that the items are filtered but for every loop "tObject" has the same values of the starting item so at the end of the loop i have an object filtered only by the last id in the array. How can I remove all the items from the state, with or without "filter". Thanks.
Upvotes: 0
Views: 43
Reputation: 2620
let rObject = this.findTimers(projectId);
let values = Object.values(rObject);
let tObject = this.state.timers.filter(timer => values.indexOf(timer.id) === -1);
this.setState({
timers: tObject
});
that will solve it, with one filter only... values
has all the values that needs to be avoided
edit: you could also do for the filter (timer => !values.includes(timer.id))
instead of the values.indexOf(...)...
Upvotes: 2