I know I can create JSON format of data in javascript
data = JSON.parse(localStorage.something);
data[0] == "some data";
But when i try to delete its not working.
delete data[0];
delete data[0] will only delete that item from the data array, which is NOT the localStorage item (since, as you already know, that item is a string).
You have to save your changes. Also I would suggest using data.shift() as per minitech's comment instead of delete - delete is better for object properties, not array indices.
data = JSON.parse(localStorage.something);
data.shift(); // delete data[0] without breaking sequence
localStorage.something = JSON.stringify(data);
After you do:
data = JSON.parse(localStorage.something);
Then the data variable holds an idependent object which from now is completely detached from localStorage (which stores just a String that need to be parsed anyway, not a 'real' object).
If you change it, you need to manually update the local storage like that:
localStorage.setItem("something", JSON.stringify(data));
As a side note: if you are aiming at older browsers, then make sure you include something like json2.js to make JSON object work everywhere.
Related
I'm having issues with the logic of using Local session variables. So I understand that HTML5 allows you to set and get these local storage variables.
I've read through this post: adding objects to array in localStorage
and understood that by using SetItem, you will rewrite the variable that you have set and thus for a dynamic array, you will need to get the variable first before pushing a new value.
So the problem I'm having, and I dont't even know if it's possible, is that I want to have, for example, a index.html page which accepts a user input and adds it into an array that needs to be persistent. When the user reloads the same page, the previous input will still be in the same array. From what I read from the post mentioned previously, you will rewrite the variable if you use SetItem. However, if I don't use setItem, how will I be able to specify that the array is to be a local Storage variable... I'm sorry if I confused anyone... because I am quite confused myself. Thanks in advance.
All of your assumptions are correct. You can only write to localStorage using setItem, and when setItem is called, you overwrite whatever value exist there. Therefore, the only way to add an item to an array in localStorage is to get the array from localStorage, manipulate it and then put it back with the new items.
// Check if we already have an array in local storage.
var x = localStorage.getItem("myArray");
// If not, create the array.
if (x === null) x = [];
// If so, decode the array.
else x = JSON.parse(x);
// Add our new item.
x.push("value 1");
// Encode the array.
x = JSON.stringify(x);
// Add back to LocalStorage.
localStorage.setItem("myArray", x);
This could done by the following approach:
var myInput = document.getElementById("myInput").value; // user data
var myList = JSON.parse(localStorage.getItem("myList")); // retrieve the list from LS
if(!Array.isArray(myList)) { // if LS list is not ok, instantiate new array
myList = [];
}
myList.push(myInput); // append user data to the list
localStorage.setItem("myList", JSON.stringify(myList)); // save the list back to LS
I have some troubles trying to put information to a input text, the info is from localstorage:
key=client,value:
[{"identification":"123456","firstname":"John","lastname":"White","tel":"123456789"}]
and my question is how can i set the identificacion, firstname, lastname and tel to a inputs type text. Im trying with this jquery
$('#name').val(localStorage.getItem("name"));
but im taking the key, no the values.
Thanks for your help!
this is your localStorage
{client: "[{"identification":"123456","firstname":"John","lastname":"White","tel":"123456789"}]", se:fkey: "65d75836cdfe6220e7d8fd44a52ef14e,1438917914"}
to save it to the localStorage Object you need to make any object into a string first
you can do it using JSON.stringify(object)
to save it to your localStorage use localStorage.setItem('key', 'value')
and when you want to fetch it on the localStorage
you can do it using localStorage.getItem('key')
if your item is a json object converted into string
you can make use JSON.parse(string) to bring back to be a json object
First get the data from the localStorage and store them in a variable. Then convert your variable from string to valid JSON format. And finally access the needed data. Here is an example :
var client = JSON.parse(storage.getItem(YOUR_CLIENT_KEY));
...
$('#name').val(client[0].firstname);
Local storage (and session storage) are key/value stores where both the keys and values are strings.
So, when pulling data out of localStorage, it will be a string. In your case, you've stored a JSON object in storage, so to use this as an object, you need to get the string out of localStorage and then use JSON.parse to parse the string and convert it to an object, then you can use the object's properties with your jQuery code:
var data = localStorage.getItem("client");
if(data) {
var obj = JSON.parse(data);
$('#name').val(obj[0].firstName + " " + obj[0].lastName);
}
Be aware that JSON.parse() can throw errors if the string is not valid JSON, so you may want to wrap this call in a try/catch block.
You should log localStorage first to see what is stored in it.
It's weird if the value is
[{"identification":"123456","firstname":"John","lastname":"White","tel":"123456789"}]
because only string type can be stored in localStorage. So you may store the array above via:
localStorage.setItem('key', JSON.stringify(array_above));
Do:
var data = JSON.parse(localStorage.getItem('key'));
when you want to retrieve it.
What's more, your code:
$('#name').val(localStorage.getItem('name'));
works fine.
Here is my jsfiddle demo.
I need to transfer a multi-dimensional JavaScript array to another page, without using any library. What I can use is JavaScript, PHP and other languages that doesn't need a library.
I have a three-dimensional array which is build like this:
storage[category][field][multiple answers] and has a lot of values.
I need to transfer it to another page so I can get all the values like:
alert(storage[5][4][8]);
=======================================================================
Well, I can pass a normal variable to another page but I cant get the values from my array when I'm testing: storage[1][1][1] for example.The big question is how I can pass a multidimensional array to another page and still be able to get the values like this: storage[1][1][1]
As I get it I'm forced to pass all the 121 arrays you can se below to be able to access all dimensions in the array.
My array is built up like this:
storage = new Array();
for (var i1=1;i1<12;i1++){
storage[i1] = new Array();
for (var i2=1;i2<12;i2++){
storage[i1][i2] = new Array();
}
}
Without using a library like jQuery, you can convert your array to JSON, pass it via a URL and decode it on the target page. Converting it to JSON would look like:
var json_string = JSON.stringify(your_array);
Then pass it in a URL:
var your_url = "http://www.your_website.com/page.html?json_string=" + json_string;
And you could decode it back to an array like so:
var your_new_array = JSON.parse(getUrlVars()["json_string"]);
For some more reading, check out this JSON page: http://www.json.org/js.html
JSON.stringify() is supported by all major browsers. Send it to the server via a POST, then have your php retrieve the variable from $_POST and send it back.
As far as I can see there are two main ways to do what you want:
Pass the array to the webserver, and have it send it back on next request.
Store the data locally in the browser.
The first way could get pretty complicated. You would have to store the data in a database, file or cookie/session.
The second way would be the easiest. Use javascript to store the array in the browser. You can either use a cookie, or use the localStorage object.
Using a cookie would require you to serialize the data manually. It would also get passed to the server, so if you want to save bandwidth, you would want to avoid this.
The localStorage method would only store the data locally, and you also don't need to serialize anything, the browser takes care of this for you.
See the links below for more examples.
http://www.w3schools.com/html/html5_webstorage.asp
http://www.w3schools.com/js/js_cookies.asp
I'd like to save off values of a tree-like structure locally, then retrieve them based on user interaction. After some research, I found that sessionStorage (or localStorage) might be a good way to go about doing this. But I'm having trouble saving nested data.
Normally you have:
sessionStorage['key'] = 'someString';
I tried to implement something like:
sessionStorage['key1'] = [];
sessionStorage['key1']['key2'] = 'someString';
but I got an undefined error.
I've checked out few other storage libraries, but they only offer that single key-value pair option. Is there anything I'm missing?
Use JSON to serialise the nested data into a string, then decode it when you need to access it as an object...
var nested = {some:{nested:'object'}}
var asJson = JSON.stringify(nested)
sessionStorage['data'] = asJson
var asObject = JSON.parse(sessionStorage['data'])
From developer.mozilla.com:
The DOM Storage mechanism is a means through which string key/value
pairs can be securely stored and later retrieved for use.
Hence I think you cannot store array/dictionary directly in session storage. I highly suggest you that check this link out:
https://developer.mozilla.org/en-US/docs/DOM/Storage
I am using Greasemonkey/Tampermonkey to visit pages and make a change to a 100-element table based on what's on the current page.
Short term storage and array manipulation works fine, but I want to store the data permanently. I have tried GM_getValue/GM_setValue, GM_SuperValue, localStorage, and indexedDB, but I am clearly missing something fundamental.
Nothing seems to allow me to write the array into the permanent storage and then read it back into a variable where I can access each element, such that variablename[32] is actually the 32nd element in the table (Well, 33rd if you start counting at zero, which I do).
I need access to the entire 100-element table while the script is running, because I need to output some or all of it on the page itself. In the most basic case, I have a for loop which goes from 0 to 99, printing out the value of variablename[i] each time.
I have no predisposition to any method, I just want the frickin' thing to work in a Greasemonkey/Tampermonkey script.
Towards the top of the script I have this:
for (var i = 0; i <= 99; i++) {
currentData[i] = localStorage.getItem(currentData[i]);
}
The purpose of the above section is to read the 100 entries into the currentData array. That doesn't actually work for me now, probably because I'm not storing things properly in the first place.
In the middle, after modifying one of the elements, I want to replace it by doing this:
localStorage.setItem(
currentData[specificElementToChange], differentStuff);
The purpose of the above is to alter one of the 100 lines of data and store it permanently, so the next time the code at the top is read, it will pull out all 100 entries, with a single element changed by the above line.
That's the general principle.
I can't tell if what I'm doing isn't working because of some security issue with Firefox/Chrome or if what I want to do (permanently storing an array where each time I access a given page, one element changes) is impossible.
It's important that I access the array using the variable[element] format, but beyond that, any way I can store this data and retrieve it simply is fine with me.
I think you're going about this wrong. LocalStorage stores strings so the simplest way to store an array in LocalStorage is to stringify it into JSON and store the JSON. Then, when reading it back, you parse the JSON back into an array.
So, to read it in, you do this:
var currentData = JSON.parse(localStorage.getItem("currentData") || "[]");
To save your data, you do this:
localStorage.setItem("currentData", JSON.stringify(currentData));
Working demo: http://jsfiddle.net/jfriend00/6g5s6k1L/
When doing it this way, currentData is a variable that contains a normal array (after you've read in the data from LocalStorage). You can add items to it with .push(), read items with a numeric index such as:
var lastItem = currentData[currentData.length - 1];
Or, change an item in the array with:
currentData[0] = "newValue";
Of course, it's just a normal array, so you can use any array methods on it.