Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a multiple values for a single key using local storage

As we all know local storage is a key value pair. Trying to create a multiple values to a single key. But unable to get how to pass the multiple values for a single key.

Here it is simple what have created.

var value = "aa"
localStorage.setItem("testKey", value);
var test = localStorage.getItem("testKey");
alert(test);

Now here what want to achieve is testKey should have aa, bb and cc values.

If it is possible can anyone please help me out with a sample.

Note:

Will localStorage values work for native app.

like image 960
user1853128 Avatar asked Jul 03 '14 04:07

user1853128


People also ask

How can I store multiple values in localStorage with same key?

Here it is simple what have created. var value = "aa" localStorage. setItem("testKey", value); var test = localStorage. getItem("testKey"); alert(test);

How do I set multiple values in local storage?

If you want to store two different values in localStorage then you can do somrthing like this : setItem in localStorage two times with different keys. localStorage. setItem("message", taskMessage); localStorage.

Can we store number in local storage?

@nickalchemist: Yes, you can store an integer value in localStorage and get it back out (as an integer).


Video Answer


2 Answers

This is not possible with localstorage. However, you can store a JSON string as the value for the key, and with a little post-processing, you can extract your three variables:

var value = ["aa","bb","cc"]
localStorage.setItem("testKey", JSON.stringify(value));
var test = JSON.parse(localStorage.getItem("testKey"));
alert(test);
like image 164
Azmisov Avatar answered Oct 05 '22 23:10

Azmisov


A single key can only have a single string value in localStorage. You can have multiple keys with different names, or you can do some encoding of the values. For example, you could put all your values in an Array, then encode it using JSON.stringify() and store the result in localStorage. When you read the data back, you can use JSON.parse() to turn it back into an Array.

like image 28
flamingcow Avatar answered Oct 06 '22 01:10

flamingcow