coder
coder

Reputation: 1929

Change key value in localStorage?

I have a localStorage item named as "1" and containing "something".

I want to change the name to "2" and leave the contents intact. How can I do that?

I know that I can copy the entire contents to "2" and then delete "1" but is there any other direct method?

Upvotes: 4

Views: 6948

Answers (1)

Philipp
Philipp

Reputation: 69663

You can take a look at the official specification.

The storage interface looks like this:

interface Storage {
      readonly attribute unsigned long length;
      DOMString? key(unsigned long index);
      getter DOMString getItem(DOMString key);
      setter creator void setItem(DOMString key, DOMString value);
      deleter void removeItem(DOMString key);
      void clear();
    };

As you see, there is no move- or rename method. So the only way to change the key of data is by using getItem to get the data from the old key, setItem to put it to the new key and removeItem to remove the old key.

When you feel the frequent need to change keys, you should reconsider if the information you use as key is really suitable for the job.

Upvotes: 8

Related Questions