Please see the function below, it works if I'm deleting the first object in the array, visually the item is deleted and the local storage is updated, however if I delete the second or another item it doesn't work, the function keeps the first item anyways and delete all the rest. Please let me know what I'm doing wrong.
const deleteNote = (event) => {
let data = Array.from(JSON.parse(localStorage.getItem("notes")));
data.forEach((note) => {
if (note.note === event.value) {
data.splice(data.indexOf(note), 1);
}
});
localStorage.setItem("notes", JSON.stringify(data));
event.parentElement.remove();
};
CodePudding user response:
You could remove the elements using the array filter
method.
const deleteNote = (event) => {
let data = Array.from(JSON.parse(localStorage.getItem("notes")));
data = data.filter((note) => note.note !== event.value);
localStorage.setItem("notes", JSON.stringify(data));
event.parentElement.remove();
};
CodePudding user response:
You can use a filter method like the below code.
const deleteNote = (event) => {
let data = Array.from(JSON.parse(localStorage.getItem("notes")));
data = data.filter(nodte => note.note !== event.value);
localStorage.setItem("notes", JSON.stringify(data));
event.parentElement.remove();
};
CodePudding user response:
if event is an Event Object, you needs get the node element from event.target
const deleteNote = (event) => {
let data = Array.from(JSON.parse(localStorage.getItem("notes")));
data.forEach((note, i) => {
if (note.note === event.target.value) {
data.splice(i, 1);
}
});
localStorage.setItem("notes", JSON.stringify(data));
event.target.parentElement.remove(event.target);
};