Cookies, objects and JSON - javascript

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)

Related

How to get the "typeof" in JavaScript for a json message

When i try to get the type of an element using the below code it works.
var bodyContent = JSON.parse(response.content);
response.content = typeof bodyContent.CompanyList.Company.Name;
Output response for above was String
Whereas if i try it in the below approach this does not work for the same JSON message. Please help
var bodyContent = JSON.parse(response.content);
var nameHolder = "CompanyList.Company.Name";
response.content = typeof bodyContent[nameHolder];
Output was undefined
That's because it's a nested object, you can't just pass a period delimited name and have it recursively drill down the tree (you'll have to implement that yourself).
It's the difference between
bodyContent["CompanyList"]["Company"]["Name"]; // former
and
bodyContent["CompanyList.Company.Name"]; // latter
There are 2 solutions for this issue.
You have to parse the nameHolder path. Reference: Accessing nested JavaScript objects with string key
or use eval but I'll not write about this since it's not a good practise.
It looks for a property called "CompanyList.Company.Name".
This works:
var bodyContent = JSON.parse(response.content);
var list = "CompanyList";
var company = "Company";
var name = "Name";
response.content = typeof bodyContent[list][company][name];

How to store JSON with array in a localStorage (Javascript)?

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 '{}'

Cookie name and value into Array

I'm trying to get all of the domain's cookies and store the name and the value into two separate arrays. Let's say I got the cookies with document.cookie and parsed it into an array:
["cookie0=value0","cookie1=value1"]
How could I extract the name and the values and turn it into two separate arrays? Should be like this:
var cookie_names = ["cookie0","cookie1"]
var cookie_values = ["value0","value1"]
I've tried to extract them with .split, but have no clue how to implement them.
Can you try out this function
function myFunction () {
var cookie_names = [];
var cookie_values = [];
var cookies = ["cookie0=value0","cookie1=value1"];
var count = 0;
for(var i in cookies){
cookie_names[count] = cookies[i].split("=")[0];
cookie_values[count] = cookies[i].split("=")[1];
count++;
}
console.log(cookie_names);
console.log(cookie_values);
}
But you have to make sure that cookies array should be in the proper format so that it can be splitted by =. In my opinion, it would be much easier of you can make the cookies array an JS Object.
eg: var cookies = {"cookie0" : "value0", "cookie1" : "value1"}
In which case you can change the for loop into this
for(var i in cookies){
cookie_names[count] = i;
cookie_values[count] = cookies[i];
count++;
}

Javascript create object with property as dynamic objects

I tried a lot searching and didnt get desired solutions.
What I want to achieve is
var myObject {
id1 : {
name:place_name,
location : place_loc
},
id2 : {
name:place_name,
location : place_loc
},
id3 : {
name:place_name,
location : place_loc
}
}
What I want to do is that Initially I want the properties "id1", "id2".. to be dynamic. And then dynamically assign name:place_name and other properties of each property.
I dont know the number of properties (id1,id2,id3...) hence would like to add them dynamically and following the addition of properties(id1,id2... ) I want to dynamically add the property values. (place_name & place_loc) of each id.
My code looks something like this.
var myObject = {};
myObject[idnumber1].place = "SomePlace1";
myObject[idnumber1].place = "SomeLoc1";
myObject[idnumber2].place = "SomePlace1";
myObject[idnumber2].place = "SomeLoc1";
But it gives error.
I know it seems simple doubt but any help would be grateful.
Thanks in advance. :)
You are trying to set a value of already assigned objects at keys "idnumber1", etc.
What you'll need is to initialize each objects for your ids like this:
var myObject = {};
myObject[idnumber1] = {};
myObject[idnumber1].place = "SomePlace1";
myObject[idnumber2] = {};
myObject[idnumber2].place = "SomeLoc1"
I would do it this way, it's not exactly what you did ask for, but I think it will become easier to change this later on.
function Place(name, location) {
this.name = name;
this.location = location;
}
var myObject = {}
myObject['id1'] = new Place('Foo', 'Bar');
myObject['id2'] = new Place('Internet', 'test');
console.log(myObject);
To dynamically create objects in your collection, you can use a numerical counter variable to create your object collection (myObject["id" + i] = {name: place_name, location: place_loc}).
An example:
var myObject = {};
for (i = 0; i < 20; i++){
myObject["id" + i] = {name: place_name, location: place_loc}
}
In practice, you can use a counter that you increment outside of a loop.

javascript message queue

I am using javascript to create a message queue, say for example I want to store the messages "hello" and "word" to user with id "123", I am using the following to set and retrieve them.
var messages = [];
var userId = 123;
messages[userId].push("hello");
messages[userId].push("word");
needless to say, this is not working, damn arrays! How can I make this work, keeping it as simple as possible?
Thanks in advance
You need an array ([]) for every user:
var messages = {};
var userId = 123;
messages[userId] = ["hello", "word"];
You can use push too:
var messages = {};
var userId = 123;
messages[userId] = [];
messages[userId].push("hello");
messages[userId].push("word");
messages[userId] does not exist.
You need to put an array there:
messages[userId] = [];
well, technically you could push elements as properties of an object, which you have created and then iterate thorugh its properties.

Categories