-1

in an array that has multiple object{} but i want a delete an object from local storage for our choice


function del(e){
  let parenttag=e.parentElement.parentElement;
let td=parenttag.getElementsByTagName('td')[2];
let match=td.innerText;
// console.log(typeof match);
let studen=localStorage.getItem('student');
let student=JSON.parse(studen);

// for(let key in student){
//     if(student[key].rollnumber===match){
//     console.log(key + ":" +student[key]);
//     console.log(student[key]);
//     }

// }

student.filter((item)=>{
    if(item.rollnumber!==match){
        return false;
    }
    console.log(item);
    localStorage.removeItem(item);
    return item;

})

i tried filter function but a unique object is show that i target but it cannot remove from local storage.

0

1 Answer 1

0

localStorage.removeItem() takes an Key, if you want to remove an item inside your array you need to use localStorage.setItem() again. To "Update" the Item.

function del(e) {
    // Get the rollnumber from the clicked row
    let parentTag = e.parentElement.parentElement;
    let td = parentTag.getElementsByTagName('td')[2];
    let match = td.innerText;

    // Get the students array from local storage and parse it
    let storedData = localStorage.getItem('student');
    if (!storedData) return;
    let studentsArray = JSON.parse(storedData);

    // Filter the students array to exclude the student with the matching rollnumber
    let updatedStudents = studentsArray.filter(item => item.rollnumber !== match);

    // Update local storage with the new array
    localStorage.setItem('student', JSON.stringify(updatedStudents));
}

The main change here is that after filtering the array to exclude the student with the matching rollnumber, we then update the local storage with the new array. The setItem method will overwrite the previous array in local storage with the updated one.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.