How to delete an item from an array from localstorage onclick
value
is the ID of an element, but ls_data
is an array of objects, not IDs. So ls_data.indexOf(value)
will not find the object in the array. And even if value
were an object, this wouldn't work because object equality is based on identical objects in memory, not comparing contents.
You need to use findIndex
to match the id
property of an array element.
function lsdel(storage_name, value) {
if (localStorage.getItem(storage_name) === null) {} else {
var ls_data = JSON.parse(localStorage.getItem(storage_name));
var index = ls_data.findIndex(({id}) => id == value);
console.log("selected index:" + index);
if (index == -1) {
// if not matched selected index
} else {
// is matched, remove...
ls_data.splice(index, 1);
localStorage.setItem(storage_name, JSON.stringify(ls_data));
console.log(ls_data);
}
}
}