I am developing a game in HTML5 for my project, my problem is in the scoring system.
I want to display the top ten best scorers (already sorted). I am currently working with Array in a JSON.
Now I want to save JSON Array in localStorage
var storage = '{"Players":[' +
'{"score":"0","Name":"Player 2"},' +
'{"score":"0","Name":"Player 4"},' +
'{"score":"0","Name":"Player 1"}]}';
var obj = JSON.parse(storage);
obj['Players'].push({"score": 13,"Name": "Player1"});
obj['Players'].push({"score": 523,"Name": "Player2"});
obj['Players'].push({"score": 3,"Name": "Player3"});
obj['Players'].push({"score": 1235,"Name": "Player4"});
storage = JSON.stringify(obj);
var sortColumnScore = "score";
function SortByScore(x,y) {
return ((x[sortColumnScore] == y[sortColumnScore]) ? 0 : ((x[sortColumnScore] < y[sortColumnScore]) ? 1 : -1 ));
}
obj.Players.sort(SortByScore);
for (var i = 0; i < 5; i++) {
document.getElementById("s"+ (i+1)).innerHTML =
obj.Players[i].score;
document.getElementById("p"+ (i+1)).innerHTML =
obj.Players[i].Name;
};
Basically you should use localstorage just like you are doing with storage above. You can use localstorage in the object way as is doing #Magus or in the associative-array way, calling its primitives getItem, setItem.
Simple usage:
var storage = '{"Players":[' +
'{"score":"0","Name":"Player 2"},' +
'{"score":"0","Name":"Player 4"},' +
'{"score":"0","Name":"Player 1"}]}';
var obj = JSON.parse(storage);
obj['Players'].push({"score": 13,"Name": "Player1"});
obj['Players'].push({"score": 523,"Name": "Player2"});
obj['Players'].push({"score": 3,"Name": "Player3"});
obj['Players'].push({"score": 1235,"Name": "Player4"});
localStorage.setItem('Players', JSON.stringify(obj));
Then get data from localStorage calling:
var myobj = JSON.parse(localStorage.getItem('Players'));
Advanced usage:
For correct usage (coupled with the current user session) and initialization of localstorage/sessionstorage (according to your goal) see the comment of #War10ck following this issue Push JSON Objects to array in localStorage.
The localStorage can't contains object or array. But you can convert it in a string.
// Store the object
localStorage.myObject = JSON.stringify(myObject);
// Read the object
var myObject = JSON.parse(localStorage.myObject);
Getting an item from localStorage:
var str = localStorage.getItem('my-item');
Saving an item in localStorage:
localStorage.setItem('my-item', str);
Note: You can only save strings to the localStorage, so, you will need to convert your data to string via JSON.stringify and then use JSON.parse when retrieving the strings from localStorage.
// To store object into local storage
localStorage.setItem('any-unique-key', JSON.stringify(arrayName));
// To retrieve from local storage
var resultArray = JSON.parse(localStorage.getItem('any-unique-key') || '{}');
// Check if the data associated with that 'any-unique-key' exists or not
// If not then return empty JSON object enclosed with single quotes
return '{}'
Related
I am trying to save my variables in an array. Theses variables are written in by the user and saved to localStorage when a button is pressed. On my other html page i reach these variables and put them in 3 different arrays(the variables, that go in three arrays). Then the user writes in new text and save to the variables. Now to the problem. The newly created variables don't add to the array, they replace. I'm thinking this is due to to the same variable name however I can't find an solution.
I have tried to change variable names etc for saving the new variable but cant find solution.
//This is html page 2 (gets the items from localhost)
var TankaKostnadVar = localStorage.getItem("StorageKostnadVar");
var TankaLiterVar= localStorage.getItem("StorageLiterVar");
var TankaDatumVar = localStorage.getItem("StorageDatumVar");
var arrayKostnad = [];
var arrayLiter = [];
var arrayDatum = [];
arrayKostnad.push(TankaKostnadVar,);
arrayLiter.push(TankaLiterVar,);
arrayDatum.push(TankaDatumVar,);
document.write(arrayLiter,arrayKostnad,arrayDatum); //Ignore this, just test
//This is the code where the user is writing and it saves to localStorage.
//Html page 1 that saves the variables
var TankaKostnadVar = document.getElementById("tankaKostnad").value;
var TankaLiterVar = document.getElementById("tankaLiter").value;
var TankaDatumVar = document.getElementById("tankaDatum").value;
localStorage.setItem("StorageKostnadVar", TankaKostnadVar);
localStorage.setItem("StorageLiterVar", TankaLiterVar);
localStorage.setItem("StorageDatumVar", TankaDatumVar);
I expect the array to add the variable. So if the user writes an 5 the array should first be [5] then when the user writes an 8 the array should be [5,8]
If you don't want use JSON, you can save string comma separated and, when necessary, transform the items to numbers. To transform in numbers you can use map function or a for. Localstorage only save strings, so if you need to be back to numbers you need to use JSON.parse or use function parseInt, that is global.
//Retrieve saved items from localstorage
var TankaKostnadVar = localStorage.getItem("StorageKostnadVar"); // "1,2"
var TankaLiterVar = localStorage.getItem("StorageLiterVar");
var TankaDatumVar = localStorage.getItem("StorageDatumVar");
TankaKostnadVar += "," + document.getElementById("tankaKostnad").value;
TankaLiterVar += "," + document.getElementById("tankaLiter").value;
TankaDatumVar += "," + document.getElementById("tankaDatum").value;
localStorage.setItem("StorageKostnadVar", TankaKostnadVar);
localStorage.setItem("StorageLiterVar", TankaLiterVar);
localStorage.setItem("StorageDatumVar", TankaDatumVar);
// if you want to transform TankaKostnadVar and others two, just do like this
TankaKostnadVar.split(','); // result: ['1', '2']
// if you want to transform to number
TankaKostnadVar = TankaKostnadVar.split(',').map( function(number) {
return parseInt(number)
} );
The split function of string, breaks a strings in parts separated by one string. In this case, breaks a string separated with comma. So "1,2" turns into ['1', '2'].
If you want to keep adding to the array you'll need to push the entire array you're holding in memory up to localStorage after appending a new element. Alos, localStorage only stores string values so if you want to maintain the Array structure you'll have to use JSON.stringify() before running setItem() and then JSON.parse() next time you access those values with getItem().
//This is the code where the user is writing and it saves to localStorage.
//Html page 1 that saves the variables
var TankaKostnadVar = document.getElementById("tankaKostnad").value;
var TankaLiterVar = document.getElementById("tankaLiter").value;
var TankaDatumVar = document.getElementById("tankaDatum").value;
localStorage.setItem("StorageKostnadVar", JSON.stringify( [TankaKostnadVar] ));
localStorage.setItem("StorageLiterVar", JSON.stringify( [TankaLiterVar] ));
localStorage.setItem("StorageDatumVar", JSON.stringify( [TankaDatumVar] ));
//This is html page 2 (gets the items from localhost)
var TankaKostnadVar = localStorage.getItem("StorageKostnadVar");
var TankaLiterVar = localStorage.getItem("StorageLiterVar");
var TankaDatumVar = localStorage.getItem("StorageDatumVar");
var arrayKostnad = JSON.parse(TankaKostnadVar);
var arrayLiter = JSON.parse(TankaLiterVar);
var arrayDatum = JSON.parse(TankaDatumVar);
// Now you have arrays with data, but I don't know what you want to do with them...
// you could add more values like this (still page 2)...
arrayKostnad.push('new value 1')
arrayLiter.push('new value 2')
arrayDatum.push('new value 3')
localStorage.setItem("StorageKostnadVar", JSON.stringify( arrayKostnad ));
localStorage.setItem("StorageLiterVar", JSON.stringify( arrayLiter ));
localStorage.setItem("StorageDatumVar", JSON.stringify( arrayDatum ));
// now check the values again
var TankaKostnadArr = JSON.parse(localStorage.getItem("StorageKostnadVar"));
var TankaLiterArr = JSON.parse(localStorage.getItem("StorageLiterVar"));
var TankaDatumArr = JSON.parse(localStorage.getItem("StorageDatumVar"));
document.write(TankaKostnadArr, TankaLiterArr, TankaDatumArr)
And this is what I would do to clean things up a little...
// Import these functions and variables to any file that needs to interact with LocalStorage
var storageKeys = ["StorageKostnadVar","StorageLiterVar","StorageDatumVar"];
function addToArray(key, val, arrObj) {
arrObj[key].push(val)
}
function storeAllLocalStorage(arrayObject) {
Object.keys(arrayObject).forEach(key=>{
localStorage.setItem(key, JSON.stringify(arrayObject[key]));
})
}
// Use above functions when needed
var storedArrays = storageKeys.reduce((acc,key)=> {
var val = JSON.parse(localStorage.getItem(key));
if (typeof val === 'array') return {...acc, [key]:val};
return {...acc, [key]:[val]};
},{})
addToArray("StorageKostnadVar", document.getElementById("tankaKostnad").value, storedArrays);
addToArray("StorageLiterVar", document.getElementById("tankaLiter").value, storedArrays);
addToArray("StorageDatumVar", document.getElementById("tankaDatum").value, storedArrays);
storeAllLocalStorage(storedArrays)
You are simply using localStorage.setItem which saves your values with the given key. If the key exists, it will replace the value. Before you do a .setItem, get the value from the local storage first, then parse it to array so that you can finally push the new user inputs to that parsed array. Then you can .setItem to replace the "outdated" value from the localStorage.
UPDATE Example:
Sorry for leaving this hangin without an example. Here it is:
// Get array from local storage
const stringifiedArray = localStorage.getItem('myCollection');
// If there is no 'myCollection' from localStorage, make an empty array
const myCollection = stringifiedArray ? JSON.Parse(stringifiedArray) : [];
myCollection.push('My new item added'); // update array
localStorage.setItem('myCollection', JSON.stringify(myCollection)); // save
I save some items in localstorage and stringify the key value before storing it.
localStorage.setItem(this.set_name, JSON.stringify(this.description))
That gives me key:
item1 Value: [{"description": "some description that was store"}, {"description": "some description that was store"}]
When i get the key value with JSON.parse it returns as an Object Object as expected, So without doing the JSON.parse it will return the whole value as is.
What I want to do is to return what's inside the description only, the "some description that was store" and not the whole value.
How would I do it?
function loadStorage() {
$itemSection = $("#item-section-set");
var keys = Object.keys(localStorage),
i = 0,
key;
for (; key = keys[i]; i++) {
let itemDesc = localStorage.getItem(key);
console.log(JSON.parse(itemDesc))
}
}
Console gives me '(3) [{…}, {…}, {…}]'
You should parse it first, and then fetch it from the array.
Considering that var stringy is the data you got from your localstorage, replace it with localStorage.getItem(<your key>);
var stringy = "[{\"description\": \"some description that was store 1\"}, {\"description\": \"some description that was store 2\"}]"
var parsedArray = JSON.parse(stringy);
for(var i = 0; i < parsedArray.length; i++){
document.getElementById('area').innerHTML += '<p>'+parsedArray[i].description+'</p>';
}
<div id="area"></div>
In general i would create separate service like
storage it should make stringify on save and JSON.parse on get
also it should have inner cache object - parsed object or undefined if object is not in cache and should be extracted and parsed from localStorage
if you are aware about performance, and you can't use JSON.parse due to too large object or similar, i would try to save descriptions in separate key-value pair
like
localStorage.setItem(this.set_name, JSON.stringify(this.description));
localStorage.setItem(this.set_name+'_'+this.descriptionKey,JSON.stringify(this.description))
to have possibility to retrieve description only by descriptionKey without parsing all object
I tried to understand you problem, but m not sure if i did, still assuming, you are saving whole List/Array as an one item in single LocalStorageItem, you will have multiple descriptions in one item, so there are multiple arrays, and each array having multiple objects hence multiple descriptions, heres my solution for this problem, if you explain more i will edit the same.
function loadStorage() {
$itemSection = $("#item-section-set");
var keys = Object.keys(localStorage),
i = 0,
key;
for (; key = keys[i]; i++) {
let itemDesc = localStorage.getItem(key);
var oneLocalStorageItem = JSON.parse(itemDesc);
oneLocalStorageItem.map(function(oneObjectItem){
console.log(oneObjectItem.description);
})
}
}
Hi I have cookie which has value of serialized params.
i.e)criteria = "name=praveen&age=25&studying=false&working=true&something=value"
Now I have to update name = praveenkumar,age = 24,something = null in this cookie string. If value is null(something = null) then it should be removed from cookie. The following is the code I am using.
updateCookie({'name':'praveenkumar','age':24,'something':null})
var updateCookie = function(params) {
// split the cookie into array
var arr = $.cookie('criteria').split("&");
//loop through each element
for(var i = arr.length - 1; i >= 0; i--) {
// getting the key i.e) name,age
var key = arr[i].split("=")[0];
// if the key is in given param updating the value
if( key in params) {
// if vale null remove the element from array or update the value
if(params[key] !== null) {
arr[i] = key+"="+params[key];
}
else {
arr.splice(i, 1);
}
}
}
// join array by & to frame cookie string again
$.cookie('criteria' , arr.join("&"));
};
It is working. But I am concerned about performance if the size of cookie become more.
Way too complicated. Try this instead :
var criteria = "name=praveen&age=25&studying=false&working=true&something=value";
Turn the serialized string into a object
var obj = JSON.parse('{"' + decodeURI(criteria)
.replace(/"/g, '\\"')
.replace(/&/g, '","')
.replace(/=/g,'":"')
+ '"}')
Based on this answer. Now you can manipulate the object
obj.studying = null;
Remove null values from the object
for (prop in obj) {
if (obj[prop] == null) delete obj[prop]
}
use jQuery's $.param to get the modified object as serialized string
criteria = $.param(obj);
== name=praveen&age=25&working=true&something=value
save the updated cookie value
$.cookie('criteria', criteria);
I do not understand the concern about performance, You should never expect a browser to allow more than 4096 bytes in a cookie. If performance and size is a concern you should use localStorage. It is much faster than cookies and has capacity measured in MB's (vary from browser to browser).
Is it possible to stringify an object and then save it locally in a cookie, then retrieve it and parse it to revert it back to normal the next time the user logs on?
Tried to cram it all into once sentence. Here's an example of what I meant:
var theObject = {
oProp : 10,
oProp : true
};
var jString = JSON.stringify(theObject);
createCookie("object", jString);
var objectRetrieved = JSON.parse( readCookie("object") );
theObject = objectRetrieved;
If this is possible, what about storing each of the objects property/values individually?
Thanks in advance!
If you use jquery here is a cleaner approach to this-
Don't explicitly say JSON.Stringify.Instead of that you can set $.cookie.json = true;
Then store the object to cookie.
var myObj= { //what ever your properties }
$.cookie('myObj', myObj);
When reading back from cookie I would do
var myObj = $.cookie('myObj');
alert('Property name is ' + myObj.YourPropertyName);
Just as an alternative to cookie method, you can also use local storage like so:
var myObj = {"name":"n1","val":3,"bool":true};
localStorage.setItem('save', JSON.stringify(myObj));
var tmp = localStorage.getItem('save');
var round_trip = JSON.parse(tmp)
$.cookie("matrizTela", null);
objCookie = {};
for(var i = 1; i<vList.length;i++){
for(var z=0;z<vList[i].length;z++){
listaY = vList[i][z].childNodes[0].attributes;
listaX = vList[i][z].style;
$.each(listaY,function(key,val){
objCookie[val.nodeName] = val.nodeValue;
});
$.each(listaX,function(key,val){
metodo = "listaX."+val;
propValue = eval(metodo);
objCookie[val] = propValue;
});
console.log(objCookie);
//Need now add objCookie in my cookie in list form!
}
};
OBS: vList is matrix of lists of the DOM Object
How can I dynamically add my objCookie in list form on my cookie?
Example:
$.cookie("matrizTela", ["objCookie", "objCookie","objCookie"]);
A cookie can store only String values.
The best you can do to store an array of objects is to serialize the array and store it as a string.
$.cookie("matrizTela", JSON.stringify(yourObjectArray));
For reading it back, you can do:
yourObjectArray = JSON.parse($.cookie("matrizTela"));