-1

I use localstorage to save items (songs) as favorites. But I would also like to be able to remove the items from the array, so not the key but the value of the key. for example I have the key Songs and values of one , two, three. I would like to be able to remove two from Songs but one and three should remain.

I cant seem to figure out how to do so because all I can find is how to remove the key and not the value of the key.

answer_me
  • 3
  • 6

3 Answers3

0

Assuming your Object is structured like this;

"Songs": ["Song One", "Song Two", "Song Three"]

I don't have the code for you, but the process I would go through is;

  • Read localStorage item (localStorage.getItem('Songs'))
  • If you know the index of the item, you can then remove it. See this post for details
  • Re-save the Object to localStorage (localStorage.setItem('Songs', SongsObj)).
Community
  • 1
  • 1
itsphilz
  • 445
  • 2
  • 9
0

You need to get value of localStorage (Songs for example). Save value into variable, then change value (delete/remove some list items), then uses same key (Songs) set previous localStorage key with new value.

localStorage.setItem('Songs', [1,2,3,4,5]);
var songs = localStorage.getItem('Songs');
// ... some operations with list...
songs = [1,3,4];
localStorage.setItem('Songs', songs);
miramax
  • 11
  • 3
0

Since you don't have any source code on display I will give you quick example of how to remove single values from the clients Local Storage. You can expand on this to remove multiple values. Wouldn't want to remove all the fun

I have commented out the Localstoage and created a Songs array so this will work in the snippet. Remove /* and */ to uncomment that section and change getItem('Songs') to fit your current source code.

You will also want to remove var Songs[]; Snippet Use only

/*--Local Storage Use
// Get Songs from Local Storage
var Storage = localStorage.getItem('Songs');
//Split Songs into an Array
var Songs=Storage.split(',');
*/
// Snippet Use -- Example Values of the Songs Result
var Songs = ['Song One', 'Song Two', 'Song Three','Song Four'];
//------ Remove Single Value
var Remove = Songs.indexOf('Song Two');
alert('Old Songs List:\n'+Songs);
if (Remove > -1) {
    Songs.splice(Remove, 1);
}
alert('New Songs List:\n'+Songs);
//--Update LocalStorage
//localStorage.setItem('Songs',Songs);

If you have any questions about the above example please leave a comment below and I will get back to you as soon as possible.

I hope this helps. Happy coding!

NewToJS
  • 2,664
  • 3
  • 12
  • 22