Save array in local storage - javascript

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!
}

Related

How to store a JavaScript object with methods in local storage?

I have a neural network library that I'm creating that contains nested objects stored in arrays. I need to be able to save the states of these objects to local storage. I've attempted to use JSON.stringify to convert the highest level network object into something I can save, but when I JSON.parse() it back, it doesn't contain the methods.
The code can be found here.
Thanks in advance for your help.
Most of them won't recommend persisting function(behavior) inside JSON object, that is intended to carry only data.
In case if you want to serialize the object with function, you need to override them, the below code would help you that.
This will help you to serialize function.
var json = function(obj){ return JSON.stringify(obj, function(key, value) {
if (typeof value === 'function') {
return value.toString();
} else {
return value;
}
})};
I've created an object rama for testing, the output of json(rama) would be
"{\"myName\":\"Ramasamy Kasiviswanathan\",\"myfunction\":\"function(input){\\nconsole.log('input', input);\\n}\"}"
Storing in localStorage,
localStorage.setItem('ramaLocal',json(rama));
Retrieving value from LocalStorage,
ramadeserialize = eval("JSON.parse(localStorage.getItem('ramaLocal'))");
O/P would be:
Object { myName: "Ramasamy Kasiviswanathan", myfunction: "function(input){\nconsole.log('input', input);\n}" }
Reference:
json.stringify does not process object methods

Updating localstorage arrays in 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"]

How do I prevent my program from overwriting localStorage every time a button is clicked?

document.getElementById("submit").addEventListener("click", getElements)
function getElements() {
var a = document.getElementById("sample").value;
var x = new obj(a);
function store() {
localStorage.setItem('todays-values', Object.values(x));
}
store();
}
In a separate js file I then call
localStorage.getItem('todays-values');
I get the values, but if I put new inputs into my html file and click the submit button, the previous values get overwritten and replaced by the new ones. How do I store all the values that are submitted and prevent the old ones from getting replaced?
I'm very new to Javascript so I would prefer to solve this problem without the use of any additional libraries if possible.
First: it seems that you are mixing JavaScript a class with a function (here is an example: What techniques can be used to define a class in JavaScript, and what are their trade-offs?)
For example this is the class equivalent in JavaScript:
function ClassName() {
var privateVar;
this.publicVar;
function privateFunction() {}
this.publicFunction = function() {};
}
You shouldn't wrap a function in a function unless it has a meaning (beacuse it is confusing for other people otherwise), but in the example given you don't need that. Also I can't see the reason why you are creating a new object x - if you create the object right before you save it you could just save the value because the object will only contain the value from sample, so you could write something like this:
document.getElementById("submit").addEventListener("click", getElements);
function storeElements() {
var sampleValue = document.getElementById("sample").value;
localStorage.setItem('todays-values', sampleValue);
}
Back to your question:
As Kalamarico mentioned: if you write new values into todays-values you will overwrite your old values, you could simply load all old values from the localStorage append the new ones and write them back to the localStorage.
You should also note that the localStorage only takes strings, so you should stringify objects (see localStorage.setItem).
function appendValueToStorage(key, value) {
var values = JSON.parse(localStorage.getItem(key));
if (values === null) {
values = [];
}
values.push(value);
localStorage.setItem(key, JSON.stringify(values));
console.log(localStorage.getItem(key));
}
appendValueToStorage('todays-values', document.getElementById("sample").value);
The function will let you append some value for a key, you could even wrap this function again to be able to use it in your click function:
function onSubmitClick() {
appendValueToStorage('todays-values', document.getElementById("sample").value);
}
document.getElementById("submit").addEventListener("click", onSubmitClick);
With the console.log command you can see the current content of the localStorage (you could also check with the developer tools - I find the ones for chrome work the best, under the Application -> Local Storage tab you can check the localStorage of your page).
You need read more about localStorage, this is a new feature introduced with HTML5, you can take a look here and see all features.
localStorage stores your data like a JSON object, if you don't know what is JSON, you need to find info. In javascript think in objects in this way:
var myData = {
myName: 'Kalamarico',
myAge: undefined
};
This is a Javascript object, and JSON is very similar and it is a representation of objects.
localStorage API stores your data as this way, when you do:
localStorage.setItem('todays-values', Object.values(x))
localStorage saves a new entry, one key 'todays-values' and its value is an object, so, your localStorage seems:
{
"todays-values": { ... }
}
Every time you set a "todays-values" you will overwrite the key, as you are seeing, so, if you can keep old values, you need to do this manage, first you can get items in localstorage (if there are), and after you can "merge" your old value and the new value. Or you can set a new key, for example: "todays-values1" depends on your need.
If you need to store exactly one key-value pair per day, then you could add the date in the key string.
Else how about numbering the keys ("yourKey_0", "yourKey_1", ...) and also storing the current (biggest) index ("currentIndex")in local storage:
function store(value) {
newIndex = localStorage.getItem("currentIndex") + 1;
localStorage.setItem("yourKey_" + newIndex, value);
localStorage.setItem("currentIndex", newIndex);
}
If you run into problems storing integer values, convert to strings.

Storing jquery clone elements to window.localStorage

I have built a page fiddle, Now I want to store the values entered in the input to window.localStorage. Please help me doing the same.
localStorage can only store strings. Because you want to store all the items added to localStorage you will have to make a string from your list and every time, get the existing list, append, and then re-stringify. Inside your addItem click function
var names = localStorage.getItem('name');
var descriptions = localStorage.getItem('description');
if (names == null) {
localStorage.setItem('name', JSON.stringify([$('.item:last input[name*="-name"]').val()]));
localStorage.setItem('description', JSON.stringify([$('.item:last input[name*="-description"]').val()]));
} else {
names = JSON.parse(names);
descriptions = JSON.parse(descriptions);
names.push($('.item:last input[name*="-name"]').val());
descriptions.push($('.item:last input[name*="-description"]').val());
localStorage.setItem('name', JSON.stringify(names));
localStorage.setItem('description', JSON.stringify(descriptions));
}
JSON.stringify will make your list into a string to put into storage, and JSON.parse will create a list from your string from storage so you can edit the list.

Meteor Session variable not storing array

I'm working on a project with search option filters and they're updated via sessions, but I'm having some issues with the session variable actually taking the array. It works fine for non-array based values, but for instance when I pass an array with RegExp objects to be used in a mongo $in selector it doesn't work as expected. The functions work fine right up until it hits Session.set() in the code snippet below so I know I have to be doing something wrong with that:
Option.prototype.update = function () {
//updates session variable if static option
if (!this.isDynamic) {
if(Object.prototype.toString.call(this.value) === '[object Array]') {
var temp = this.value.slice(0);
Session.set(this.optionName, temp);
console.log(Session.get(this.optionName));
}
else {
Session.set(this.optionName, this.value);
}
};
};
for whatever reason instead of displaying the array with values in it, it displays
[Object], and the object in that array is empty. I've read the other Overflow posts on Session variables and arrays, and simply cloning the array before passing it doesn't seem to be working. Any idea what I'm doing wrong?
Your code is correct (although slightly convoluted). The problem is that Session only takes EJSON–able values, and regexes are not EJSON–able. From the perspective of EJSON, regex looks just like an empty object, and that's exactly what you get in the stored array. Similar problem would appear if you try to store object with custom prototype, or with private (not enumerable) properties: everything that is not serialized to EJSON is lost.
The solution here is to create your own serialization method that will work with regexes. For example, if you will always have a flat array of regexes, you could simply stringify them before storing:
var temp = _.map(this.value, function(regex) {
return regex.toString();
});

Categories

Resources