How to create a multiple values for a single key using local storage
Solution 1
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);
Solution 2
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.
Solution 3
You can actually do that, using json arrays for example you want to store this array with two items
var items = {
"1": {
"id": 7606606,
"item_id": "2",
"row": {
"id": "2",
"amount": 0,
"plan": 1
}
},
"2": {
"id": 7606623,
"item_id": "3",
"row": {
"id": "3",
"amount": 0,
"plan": 1
}
}
}
Convert that to json then store in local storage like this
localStorage.setItem('myItems', JSON.stringify(items));
then you retrieve the same way
var items = JSON.parse(localStorage.getItem('myItems'));
then you can use foreach to retrieve
user1853128
Updated on July 09, 2022Comments
-
user1853128 almost 2 years
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 haveaa, 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.
-
user1853128 almost 10 yearsThank you very much. Have doubt which already mention in the question. Does native app also store this localstorage value
-
Azmisov almost 10 yearsAs far as I know, it will work. You just have to make sure the native app supports the JSON methods.
-
Mun about 6 yearsYou can store multiple values in local storage with single key.Just you have to append after you push values into an array. i-e.localStorage.item+=
-
B N Manish over 2 yearscan't I store an array or object in local storage?