I'm working on a todo list assignment that basically consists of a user being able to create a List and within that List he would be able to create Todo items. I was working on the function to delete a todo from a given list. Now I was able to get this to work by iterating through each list, find a matching Id of the Todo item the user wants to delete, get the index of that item and use the Splice() method to remove it from the original array, all this is fine and works great but my concern is that the initial ForEach iteration will continue iterating each list even if the ID was found so my question is how do I break from the iteration once a matching ID is found? Perhaps I'm using the wrong approach to accomplish, sorry for making your eyes bleed in advance :)
const lists = JSON.parse(localStorage.getItem('lists')) || [];
generatedTrashIcon.addEventListener('click', (event) => {
deleteTodo(generatedTrashIcon.previousSibling.id);
});
const deleteTodo = (deletedTodoId) => {
lists.forEach((list) => {
const findTodo = list.todos.find((todoItem) => todoItem.id === deletedTodoId);
if (findTodo) {
const todoIndex = list.todos.indexOf(findTodo);
list.todos.splice(todoIndex, 1);
localStorage.setItem('lists', JSON.stringify(lists));
appendTodosToView(clickedListId);
}
});
};
here's how the output of the lists object is structured :
{
"id": "1622610431641",
"name": "Productivity",
"todos": [
{
"id": "1623013270585",
"todoItem": "code all day!"
}
]
}