0

I have a localStorage object like this:

Key: jpxun

Value: [{"id":"0","name":"royal"},{"id":"1","name":"tippins"},{"id":"4","name":"leviosa"},{"id":"5","name":"vicious"}]

I have this JS to display output the localStorage:

var jpxun = JSON.parse(localStorage.getItem('jpxun')) || [];

if (jpxun) {
    var jpxun_length = jpxun.length;
} else {
    var jpxun_length = 0;
}

var hst = document.getElementById("usernames");

var MyUsernames = JSON.parse(localStorage.getItem("jpxun"));

if (jpxun_length > 0) {

    // declare array to hold items for outputting later in plain text format
    var plain_text_array = [];

    for (var i = 0; i < MyUsernames.length; i++) {

        var un1 = MyUsernames[i].name;

        hst.innerHTML += "<li>" +"<a id="+MyUsernames[i].id + " href='#content' onclick='deleteById(this)'>x </a>" + un1 + "</li>";

        // add word to plain text array
        plain_text_array.push(un1);

    }

}

Each element is outputted in a list item with an 'x' as a hyperlink so that it can be clicked and that element is deleted from localStorage.

This is the code to delete the item from localStorage:

var deleteById = function ( self ){

  MyUsernames = MyUsernames.filter(function(elem) {
      return elem.id !== self.id;
  });
          
  localStorage.setItem("jpxun",JSON.stringify(MyUsernames));
  
  self.parentNode.parentNode.removeChild(self.parentNode);
  
}

That works fine.

Unfortunately I don't really understand how the code works in deleteById.

As that is the case, I am stuck on working out how to delete the corresponding record from plain_text_array when its value is deleted from localStorage.

1 Answer 1

1

I would try to find the text in the array thats includes that string 'id="item_id"':

plain_text_array = plain_text_array.filter(item => !item.includes(`id="${self.id}"`));

Just add it in the end of deleteById function.

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

4 Comments

Hi @Asaf - thanks for your reply. Does the $ in your code imply the code is jQuery code? The rest of my code isn't jQuery, which makes it tricky to plug it into the existing code. Sorry though if I'm wrong there. Thanks.
Hi it's in javascript ES6
It's more straightforward than the alternative: 'id="'+self.id+'"'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.