从本地存储中删除数组对象

问题描述 投票:0回答:1

在具有多个对象{}的数组中,但我想从本地存储中删除一个对象供我们选择


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;

})

我尝试了过滤功能,但有一个独特的对象显示我的目标,但它无法从本地存储中删除。

javascript local-storage crud
1个回答
0
投票

localStorage.removeItem() 需要一个 Key,如果你想删除数组中的一个项目,你需要再次使用 localStorage.setItem() 。 “更新”项目。

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));
}

这里的主要变化是,在过滤数组以排除具有匹配的学号的学生之后,我们用新数组更新本地存储。 setItem 方法将用更新后的数组覆盖本地存储中的前一个数组。

© www.soinside.com 2019 - 2024. All rights reserved.