Updating localstorage arrays in Javascript - javascript

I'm trying to store and update an array in the localstorage using JSON.parse/stringify. But it doesn't seem to be working.
yesArray = JSON.parse(localStorage.getItem(yesArray));
yesArray.push("yes");
localStorage.setItem("yesArray", JSON.stringify(yesArray));
Am I all wrong with this?

This seems to be the problem with passing the key of local storage without quotes.
While reading from local storage use the key as argument as it stores the value as key/value pairs.
yesArray = JSON.parse(localStorage.getItem("yesArray"));

Missing quotes around yesArray in the first line?
yesArray = JSON.parse(localStorage.getItem('yesArray'));
Sample:
var yesArray = [];
localStorage.setItem('yesArray', JSON.stringify(yesArray));
yesArray = JSON.parse(localStorage.getItem('yesArray'));
yesArray.push('yes');
localStorage.setItem('yesArray', JSON.stringify(yesArray));
JSON.parse(localStorage.getItem('yesArray')); // Returns ["yes"]

Related

How to save multiple form values as a consolidated String in Local Storage and retrieve them to be displayed on the browser

I'm trying to create a 'Notes' application which is basically a form that the user uses to enter 2 values, a name and a note.
I am displaying the 2 values as a 'consolidated note' on the browser with a delete button.
There can be any number of notes entered using this form.
How can I save the consolidated notes(i.e with Creator's name and the actual content of the note) in a string or array in the Local Storage and then retrieve it to be displayed on the browser when the browser reloads?
I understand that we save it using JSON.stringify and retrieve the data from the Local Storage using JSON.parse, but I'm unsure of how to save these multiple notes in the LOCAL Storage and retrieve them. Please help!
function addNoteLocalStorage(){
let notes = getNotesFromStorage();
//creating the key-value pairs
let creator = document.getElementById('creator').value;
let note = document.getElementById('note').value;
obj.creator = creator;
obj.note = note;
let jsonstring = JSON.stringify(obj);
//create an array and push the string to the Object Array
objArray.push(jsonstring);
//store the new note
localStorage.setItem('notes', objArray);
}
The above code saves more than one note in the Local Storage.
Currently, this is how the array looks when stored in LS.
{"creator":"dgfdxsf","note":"dsgdsg"},{"creator":"sfs","note":"asd"}
How can I retrieve the values back into an object so that I can display each creator and note associated with that creator ?
Create an object of the values you get from the form.
var obj = {
creator : note
}
Now store this object in the local storage by stringifying in the same as you are doing (JSON.stringify). While retrieving, do a JSON.parse to retrieve the object.
If you have multiple objects like these, push them into an array and store that array in the local storage.
There is no need to convert a string to a JSON string, so you can play with your data without the need for stringify() and parse(). If you save the notes as array, however, you will need to do that.
// Add Note to Local Storage
function addNoteLocalStorage(){
//get saved notes. Set notes to empty string if it's the first time.
let notes = localStorage.getItem('notes') || '';
console.log("Notes return: "+notes);
//creating the key-value pairs
let creator = document.getElementById('creator').value;
let note = document.getElementById('note').value;
let consolidatedNotesString = creator+":"+note;
//append the new note to the existing note
notes += '\n'+ consolidatedNotesString;
//store the new note
localStorage.setItem('notes', notes);
}
With your edited question, you're saving notes in the form of array of objects, in which case you will of course need to stringify and parse back the notes. One issue with your current code is that you're converting to string the objects(notes) but you save the array which contains the notes as it is. stringify the whole array instead and that's enough. And the way you access the stored notes is by the getItem method and parse it to get back the array. Make sure to save the empty objArray as notes in the local storage before calling addNoteLocalStorage function though, or you will need to check if notes are already in the storage before trying to parse it.
const objArray = [];
localStorage.setItem('notes', JSON.stringify(objArray));
function addNoteLocalStorage(){
objArray = JSON.parse(localStorage.getItem('notes'));
//creating the key-value pairs
let creator = document.getElementById('creator').value;
let note = document.getElementById('note').value;
//push the string to the Object Array
objArray.push({creator, note});
//store the new note
localStorage.setItem('notes', JSON.stringify(objArray));
}
//And to get the first note and creator for example, you write like:
let noteArray = JSON.parse(localStorage.getItem('notes'));
let firstNoteCreator = noteArray[0].creator;
let firstNote = noteArray[0].note;

How to remove double quotes from outside of an Array?

I am taking data from the multiple select that gives me an array data. The data that I am getting is
{provinces: "["1","2"]"}
and when I stringify this data I got
{"provinces":"[\"1\",\"2\"]"}
But what I really want is
{"provinces":["1","2"]}
is there any way ?
use the JSON.parse
var obj = {"provinces":"[\"1\",\"2\"]"}
obj.provinces = JSON.parse(obj.provinces);
console.log(obj)

Save array in local storage

This is my full code
I need to save the array visited to local storage. Then, I need an if statement to check if the array has been stored. If it has, it will do
return;
ending the code and making the button not functional.
Something like this;
if (store.length == 3) {
document.getElementById('btn').className = 'maxques';
alert('You have completed this category');
console.log(store);
return; }
I just somehow need to store the array. I tried JSON stringify followed by JSON parse but either they don't work or I'm doing them wrong. Any ideas?
At the risk of repeating #Tom Hart, use a combination of the functions localstorage.setItem and localStorage.getItem. Respectively params being key, value and key.
To store your array:
localStorage.userEdits=array.join(","); //or another delimiter
To check if stored:
if(localStorage.userEdits){
//stored!
}

Every character in an array being recognized with ".hasOwnProperty(i)" in javascript as true with Google Apps Script

This is the array:
{"C8_235550":
{"listing":"aut,C8_235550_220144650654"},
"C8_231252":
{"listing":"aut,C8_231252_220144650654"}}
It was fetched with a GET request from a Firebase database using Google Apps Script.
var optList = {"method" : "get"};
var rsltList = UrlFetchApp.fetch("https://dbName.firebaseio.com/KeyName/.json", optList );
var varUrList = rsltList.getContentText();
Notice the .getContentText() method.
I'm assuming that the array is now just a string of characters? I don't know.
When I loop over the returned data, every single character is getting pushed, and the JavaScript code will not find key/value pairs.
This is the FOR LOOP:
dataObj = The Array Shown At Top of Post;
var val = dataObj;
var out = [];
var someObject = val[0];
for (var i in someObject) {
if (someObject.hasOwnProperty(i)) {
out.push(someObject[i]);
};
};
The output from the for loop looks like this:
{,",C,8,_,2,3,5,5,5,0,",:,{,",l,i,s,t,i,n,g,",:,",a,u,t,,,C,8,_,2,3,5,5,5,0,_,2,2,0,1,4,4,6,5,0,6,5,4,",},,,",C,8,_,2,3,1,2,5,2,",:,{,",l,i,s,t,i,n,g,",:,",a,u,t,,,C,8,_,2,3,1,2,5,2,_,2,2,0,1,4,4,6,5,0,6,5,4,",},}
I'm wondering if the array got converted to a string, and is no longer recognized as an array, but just a string of characters. But I don't know enough about this to know what is going on. How do I get the value out for the key named listing?
Is this now just a string rather than an array? Do I need to convert it back to something else? JSON? I've tried using different JavaScript array methods on the array, and nothing seems to return what it should if the data was an array.
here is a way to get the elements out of your json string
as stated in the other answers, you should make it an obect again and get its keys and values.
function demo(){
var string='{"C8_235550":{"listing":"aut,C8_235550_220144650654"},"C8_231252":{"listing":"aut,C8_231252_220144650654"}}';
var ob = JSON.parse(string);
for(var propertyName in ob) {
Logger.log('first level key = '+propertyName);
Logger.log('fisrt level values = '+JSON.stringify(ob[propertyName]));
for(var subPropertyName in ob[propertyName]){
Logger.log('second level values = '+ob[propertyName][subPropertyName]);
}
}
}
What you have is an object, not an array. What you need to do is, use the
Object.keys()
method and obtain a list of keys which is the field names in that object. Then you could use a simple for loop to iterate over the keys and do whatever you need to do.

localStorage problems

My store uses localStorage to store the cart. I've used this line to retrieve the value:
var kamat = window.localStorage.getItem("simpleCart_items"); alert(kamat);
This will retrieve something like :
{"SCI-1":{"quantity":1,"id":"SCI-1","price":20,"name":"Valkoinen hiilikuitu -teippi","size":"Tyhjä"},"SCI-3":{"quantity":1,"id":"SCI-3","price":4,"name":"Car Speaker -hajuste","color":"Sport Fresh"}}
And as I've stored it as a variable, I want to use it a bit later.
I want to add this before the final curly bracket (after variable kamat)
var toimituskulut = {"Toimitus":{"quantity":1,"id":"Toimituskulut","price":8,"name":"Toimituskulut"}};
I've tried this as it needs a colon between the items:
var kamatjatoimituskulut = kamat + "," + toimituskulut;
But won't work. And if it would, it would insert the contents of toimituskulut after the final curly bracket. So what would I need to do?
EDIT
I'm trying to edit it when a button is clicked:
$("#posti").live('click', function() {
$(".maksu").slideDown(600);
$("#posti").attr("disabled" , "disabled");
$("#matkahuolto").removeAttr("disabled");
$("#posti").addClass( "selectedtoimitus" );
$("#matkahuolto").removeClass( "selectedtoimitus" );
$(".simpleCart_shipping").html(kamat);
var kamatObj = JSON.parse(localStorage["simpleCart_items"]);
kamatObj['toimituskulut'] = toimituskulut;
localStorage["simpleCart_items"] = JSON.stringify(kamatObj);
});
But no, it won't add a thing.
JSFIDDLE
So, if the local storage looks like this:
{"SCI-1":{"quantity":1,"id":"SCI-1","price":20,"name":"Valkoinen hiilikuitu -teippi","size":"Tyhjä"},"SCI-3":{"quantity":1,"id":"SCI-3","price":4,"name":"Car Speaker -hajuste","color":"Sport Fresh"}}
I want it to look like this when I click a button
{"SCI-1":{"quantity":1,"id":"SCI-1","price":20,"name":"Valkoinen hiilikuitu -teippi","size":"Tyhjä"},"SCI-3":{"quantity":1,"id":"SCI-3","price":4,"name":"Car Speaker -hajuste","color":"Sport Fresh"},"Toimitus":{"quantity":1,"id":"Toimitus","price":5,"name":"Toimituskulut"}}
But doing var kamatjatoimituskulut = kamat + "," + toimituskulut;
would only output something similar to this, right?
{"SCI-1":{"quantity":1,"id":"SCI-1","price":20,"name":"Valkoinen hiilikuitu -teippi","size":"Tyhjä"},"SCI-3":{"quantity":1,"id":"SCI-3","price":4,"name":"Car Speaker -hajuste","color":"Sport Fresh"}},"Toimitus":{"quantity":1,"id":"Toimitus","price":5,"name":"Toimituskulut"}
If you have two variables containing JSON strings, like this:
var kamat = '{"SCI-1":{"quantity":1,"id":"SCI-1","price":20,"name":"Valkoinen hiilikuitu -teippi","size":"Tyhjä"},"SCI-3":{"quantity":1,"id":"SCI-3","price":4,"name":"Car Speaker -hajuste","color":"Sport Fresh"}}';
var toimituskulut = '{"Toimitus":{"quantity":1,"id":"Toimituskulut","price":8,"name":"Toimituskulut"}}';
you'll need to parse those strings into json like so (I'm using jQuery):
var kamatJSON = $.parseJSON(kamat);
var toimitusJSON = $.parseJSON(toimituskulut);
and then add them together like so:
$.extend(kamatJSON, toimitusJSON);
and since it's an object, the order should'nt really matter if you access the values like:
kamatJSON.Toimitus
FIDDLE;
What you want is to add a property to an object.
But what you have is a string, as localStorage only stores strings. It seems to be stored as JSON (which is the most obvious solution).
First you need to restore the object :
var kamatObj = JSON.parse(localStorage["simpleCart_items"]);
Then you may add a property :
kamatObj['toimituskulut'] = toimituskulut;
And then you may serialize it as string again to put it back in localStorage :
localStorage["simpleCart_items"] = JSON.stringify(kamatObj);
Try This :
$("#posti").live('click', function() {
$(".maksu").slideDown(600);
$("#posti").attr("disabled" , "disabled");
$("#matkahuolto").removeAttr("disabled");
$("#posti").addClass( "selectedtoimitus" );
$("#matkahuolto").removeClass( "selectedtoimitus" );
$(".simpleCart_shipping").html(kamat);
var kamatObj = JSON.parse(localStorage["simpleCart_items"]);
var resultObject =JSON.parse((kamatObj).concat(JSON.parse(toimituskulut));
alert(resultobjcet);
localStorage["simpleCart_items"] = resultObject;
});
If you are trying to add content to an object (stringified of course), in local storage, I wrote a tool just for that purpose. It can set any type of value in local storage, and extract likewise. It can even store values nested deep within the stored values. You can find the script/tool here at https://github.com/andresgallo/truStorage
You might want to look at localDataStorage. It transparently sets/gets Arrays, Booleans, Dates, Floats, Integers, Strings and Objects. It provides lightweight data obfuscation (for security) and intelligently compresses strings. The utility lets you query by key (name) or (key) value or data type, checks for duplicate values, and supports the notion of write-protected keys. Note: I am the author of the utility.

Categories

Resources