Im probably miles off but can anyone tell me if this is possible.
function myFunction(){
var myArray = (localStorage.getItem("storedArray"));
myArray = jQuery.makeArray( myArray );
myArray.push(['someone@myemail','15','myUsername']);
localStorage.setItem("storedArray", JSON.stringify(grabArray));
localStorage.removeItem("storedArray");
}
Every time this function is ran i'm wanting to get an array from local storage push values to it and then store it back, so like updating it. The idea is that once an event happens in my application, this item will be cleared, to start logging again.
When i've got the item from local storage i've attempted to turn it back into an array but i don't think this is the way to do it as it isn't returning anything. Can anything be done with JSON?
Thanks.
Im probably miles off but can anyone tell me if this is possible.
function myFunction(){
var myArray = (localStorage.getItem("storedArray"));
myArray = jQuery.makeArray( myArray );
myArray.push(['someone@myemail','15','myUsername']);
localStorage.setItem("storedArray", JSON.stringify(grabArray));
localStorage.removeItem("storedArray");
}
Every time this function is ran i'm wanting to get an array from local storage push values to it and then store it back, so like updating it. The idea is that once an event happens in my application, this item will be cleared, to start logging again.
When i've got the item from local storage i've attempted to turn it back into an array but i don't think this is the way to do it as it isn't returning anything. Can anything be done with JSON?
Thanks.
Share Improve this question asked Apr 22, 2015 at 22:36 jord49jord49 5822 gold badges18 silver badges40 bronze badges2 Answers
Reset to default 4function myFunction() {
var storedArray = JSON.parse(localStorage.getItem("storedArray"));
if (storedArray === null) {
storedArray = [];
}
var obj = {
email: "[email protected]",
age: 15,
name: "username"
};
storedArray.push(obj);
localStorage.setItem("storedArray", JSON.stringify(storedArray));
}
Setting the updated storedArray to same key in local storage overwrites the old value. Try this code and you'll see the updated array.
Info: Local Storage data is stored as key-value.
Trott was right, you missed to parse the json that you saved.
JSON.stringify converts your json object/array into a string. In order to get back the same data you have to parse it.
If you are using JSON.stringify()
to convert the object to a JSON string representation, then you can use JSON.parse()
to convert the JSON representation back to the object.