0

Is there a way of changing a key in a localstorage? For example, if I have a key set to "4" and value of "myvalue" and I'd like to change the key to 3. What would the process be?

Would I have to getItem first and then Setitem with an index-1?

for instance, the user clicks a certain button and creates an indexed localstorage entry like so-

Then, he has the option to delete an entry which will leave him like so:

I want to call a function on page unload that reorders the keys and sets 3 to 2 (reindex it).

Ideas would be appreciated

Subjugation
  • 105
  • 2
  • 10

2 Answers2

2

You'll first have to set the new value, before deleting the old one. Like this:

function changeKey(oldKey, newKey) {
    localStorage.setItem(newKey, localStorage.getItem(oldKey));
    localStorage.removeItem(oldKey);
}

I would suggest that you do not use the localStorage as an array like that though, but instead use a single localStorage item to store your array:

var myArray = [ { a : 1 }, { b : 2 } ];

localStorage.setItem("myArray", JSON.stringify(myArray));

Then whenever you want to manipulate the array, you can do it like this, and the array indexes will update automatically:

var myArray = JSON.parse(localStorage.getItem("myArray")); // Fetching the array

myArray.splice(myIndex, 1); // Removing an item with index 'myIndex';

localStorage.setItem("myArray", JSON.stringify(myArray)); // Storing the changes
Amsvartner
  • 733
  • 7
  • 19
  • is there a way of looping through the whole Local storage? perhaps a for loop that runs till storage.length? – Subjugation Feb 08 '19 at 12:50
  • 1
    More on that... https://stackoverflow.com/questions/17745292/how-to-retrieve-all-localstorage-items-without-knowing-the-keys-in-advance – Cat Feb 08 '19 at 12:55
  • Good point, @Cat. Looping through localStorage might also be needlessly complicated; I've updated my original answer with a suggested alternative approach – Amsvartner Feb 11 '19 at 09:14
1

General approach:

function changeKeyforStorageItem(oldKey, newKey) {
   let myValue = localStorage.getItem(oldKey);
   localStorage.removeItem(oldKey);
   localStorage.setItem(newKey, myValue);
}

or :

 function changeKeyforStorageItem(oldKey, newKey) {
    localStorage.setItem(newKey, localStorage.getItem(oldKey));
    localStorage.removeItem(oldKey);
 }
iLuvLogix
  • 5,920
  • 3
  • 26
  • 43