简体   繁体   English

如何使用localstorage删除数组中的对象?

[英]How to delete object in array using localstorage?

I have to delete object in array and it should be deleted from localstorage. 我必须删除数组中的对象,应该将其从localstorage中删除。 I am trying to delete it by using splice method but not actually getting how to use it. 我试图通过使用splice方法将其删除,但实际上并没有获得如何使用它的方法。 Folloeing is my code which i have tried- Folloeing是我尝试过的代码-

 var details = [];



 function addEntry() {


   var existingEntries = JSON.parse(localStorage.getItem("allEntries"));
   if (existingEntries == null) existingEntries = [];


   var srno = document.getElementById("txtpid").value;
   var name = document.getElementById("txtpname").value;
   var dob = document.getElementById("txtpdob").value;
   var email = document.getElementById("txtpemail").value;
   var address = document.getElementById("txtpaddr").value;
   var contact = document.getElementById("txtpmobile").value;

   var obbbj = {
     txtpid: srno,
     txtpname: name,
     txtpdob: dob,
     txtpemail: email,
     txtpaddr: address,
     txtpmobile: contact
   };
   localStorage.setItem("details", JSON.stringify(obbbj));

   existingEntries.push(obbbj);
   localStorage.setItem("allEntries", JSON.stringify(existingEntries));
   showEntry();
   console.log(existingEntries);
   //location.reload();
 }


 function showEntry() {
   var messageBox = document.getElementById("display");
   messageBox.value = "";
   document.getElementById("txtpid").value = "";
   document.getElementById("txtpname").value = "";
   document.getElementById("txtpdob").value = "";
   document.getElementById("txtpemail").value = "";
   document.getElementById("txtpaddr").value = "";
   document.getElementById("txtpmobile").value = "";


   var render = "<table border='1'>";
   render += "<tr><th>Srno</th><th>Name</th><th>Birthdate</th><th>Email</th><th>Address</th><th>Contact</th></tr>";


   var allEntriesoo = {};
   var detailsOOO = {};
   for (i = 0; i < localStorage.length; i++) {
     var key = localStorage.key(i);
     var person = localStorage.getItem(key);
     if (key == 'allEntries')
       allEntriesoo = JSON.parse(person);
     if (key == 'details')
       detailsOOO = JSON.parse(person);
     var data = JSON.parse(person);

   }

   for (var key in allEntriesoo) {
     console.error(allEntriesoo[key])
     render += "<tr><td>" + allEntriesoo[key].txtpid + "</td><td>" + allEntriesoo[key].txtpname + " </td>";
     render += "<td>" + allEntriesoo[key].txtpdob + "</td>";
     render += "<td>" + allEntriesoo[key].txtpemail + "</td>";
     render += "<td>" + allEntriesoo[key].txtpaddr + "</td>";
     render += "<td>" + allEntriesoo[key].txtpmobile + "</td>";
     render += "<td><input type='button' value='Delete' onClick='return deleteEntry(" + i + ")'></td>";
     render += "<td><input type='button' value='Edit' onClick='return editInfo(" + i + ")'></td></tr>";

   }
   render += "</table>";
   display.innerHTML = render;
 }

 function nameVal() {
   document.getElementById("txtpname").focus();
   var n = document.getElementById("txtpname").value;
   var r;
   var letters = /^[a-zA-Z]+$/;
   if (n == null || n == "") {
     alert("please enter user name");
     return null;
     n.focus();
   } else {
     if (n.match(letters) && n != "") {
       r = ValidateEmail();
       return r;
     } else {
       alert("please enter alphabates");
       document.getElementById("txtpname").value = "";
       document.getElementById("txtpname").focus();
       return null;
     }
   }
 }

 function ValidateEmail() {
   var uemail = document.getElementById("txtpemail").value;
   var mailformat = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/;
   if (uemail.match(mailformat)) {
     return true;
   } else {
     alert("You have entered an invalid email address!");
     document.getElementById("txtpemail").value = "";
     document.getElementById("txtpemail").focus();
     return null;
   }
 }

 function alphanumeric() {
   var uadd = document.getElementById("txtpaddr").value;
   var letters = /^[0-9a-zA-Z]+$/;
   if (uadd == null || uadd == "") {
     alert("plz enter address");

     uadd.focus();
   } else {
     if (uadd.match(letters)) {
       return true;
     } else {
       alert('User address must have alphanumeric characters only');
       document.getElementById("txtpaddr").value = "";
       document.getElementById("txtpaddr").focus();
       return false;
     }
   }
 }

 function cntVal() {
   var n = document.getElementById("txtpmobile").value;
   var r1;
   var letters = /^\d{10}$/;
   if (n !== null || n !== "") {
     if (n.match(letters)) {
       r1 = alphanumeric();
       return r1;
     } else {
       alert("please enter contact number");
       document.getElementById("txtpmobile").value = "";
       document.getElementById("txtpmobile").focus();
       return null;
     }
   } else {
     alert("please enter contact Number");
     return null;
     n.focus();
   }

 }

 function deleteEntry(id) {
   console.log("aaaaaaaaaaaaaaAAAA");

   var entry = localStorage.getItem('allEntries') JSON.parse(localStorage.getItem('allEntries')): [];
   var index;
   for (var i = 0; i < entry.length; i++) {
     if (entry[i].id === id) {
       index = i;
       break;
     }
   }
   if (index === undefined) return
   entry.splice(index, 1);
   localStorage.setItem('entry', JSON.stringify(entry));
 }

 function clearstorage() {
   localStorage.clear();
   window.location.reload();
 }

 window.onload = function() {
   showEntry();
 };

In your deleteEntry function you are setting a new item in localStorage called 'entry'. 在deleteEntry函数中,您要在localStorage中设置一个名为“ entry”的新项目。 So you are not setting 'allEntries' and thats probably why its showing up like that, 'allEntries' has not been updated. 因此,您未设置“ allEntries”,这可能就是为什么其显示未更新“ allEntries”的原因。 So just set all entries again. 因此,只需重新设置所有条目。 localStorage.setItem('allEntries', JSON.stringify(entry)); localStorage.setItem('allEntries',JSON.stringify(entry));

You are also missing the '?' 您还错过了“?” for you variable 'entry'... 为您变量'entry'...

var entry = localStorage.getItem('allEntries') ? var entry = localStorage.getItem('allEntries')吗? JSON.parse(localStorage.getItem('allEntries')) : []; JSON.parse(localStorage.getItem('allEntries')):[]; <-- it should look like this. <-应该看起来像这样。

Its the same as an 'if else statement' 它与“ if else语句”相同

 function deleteEntry(id){ console.log("aaaaaaaaaaaaaaAAAA"); var entry = localStorage.getItem('allEntries') ? JSON.parse(localStorage.getItem('allEntries')) : []; var index; for (var i = 0; i < entry.length; i++) { if (entry[i].id === id) { index=i; break; } } if(index === undefined) return entry.splice(index, 1); localStorage.setItem('allEntries', JSON.stringify(entry)); <--- like this } 

You can use create a temporary object and then replace it in localStorage. 您可以使用创建一个临时对象,然后将其替换为localStorage。

 function deleteEntry(id){
    console.log("aaaaaaaaaaaaaaAAAA");

      var entry = JSON.parse(localStorage.getItem('allEntries'));
        var temp= [];
        for (var i = 0; i < entry.length; i++) {
            if (entry[i].id !== id) {
              temp.push(entry[i]);
            }
        }
        localStorage.setItem('entry', JSON.stringify(temp));
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM