Storing a javascript object in HTML5 local storage - javascript

I want to store a JavaScript object in HTML5 local storage.
sessionStorage.setItem("localObj",this);
I am using the above statement within a function.The object contains HTML tags.
I can neither convert it to a string nor to a JSON.
How do i proceed with this?

You have to first convert the object into json and then store in local storage. And when you want to reuse the stored data you have to deserialize the json string into javascript object and it will work fine.
Working Sample
function setValue() {
var obj = new user();
var jsonObject = JSON.stringify(obj);
sessionStorage.setItem("Gupta", jsonObject);
getValue();
}
function user() {
this.Name = "rahul";
this.Age = 20;
}
function getValue() {
var json_string = sessionStorage.getItem("Gupta");
var obj = JSON.parse(json_string)
alert("Name = "+obj.Name + ", Age = " + obj.Age);
}

Local storage will only store strings. If you can't make a string representation of your object, then you can't store it.

Local storage is designed with string / value pairs in mind, so you'll have a hard time trying to store your object 'as is'. You either need to 'stringify' it, or you need to look at something else. The answers to this earlier question should assist:
Storing Objects in HTML5 localStorage

Related

sessionStorage not storing original object

I have an object which I'm getting by executing a function of SDK. When I try to store the object in session storage and the retrieve the object, the retrieved object looks same as original but when I perform operations on the new object I'm getting error.
var xyzObject = some_function();
sessionStorage.setItem("xyzObject",xyzObject);
var obj = JSON.parse(sessionStorage.getItem("xyzObject"));
obj.some_other_function();
It is showing an error as obj.some_other_function is not a function. Whereas xyzObject.some_other_function works perfectly.
Try
sessionStorage.setItem('xyzObject', JSON.stringify(xyzObject);
And retrieve using:
JSON.parse(sessionStorage.getItem('xyzObject'));
You cannot store an object in the sessionStorage or localStorage. The only possible method is to stringify the object and save that in sessionStorage and on receiving the object from sessionStorage you just parse the object to JSON.
var xyzObject = some_function();
sessionStorage.setItem("xyzObject",JSON.stringify(xyzObject));
var stringData = sessionStorage.getItem("xyzObject");
var obj = JSON.parse(stringData);
obj.some_other_function();
sessionStorage only stores strings as values.
If you want to store an object in sessionStorage, you must stringify the object into a JSON string, using the JSON.stringify() method.
const xyzObject = { name: "Juan" };
sessionStorage.setItem("xyzObject", JSON.stringify(xyzObject);
Then if you want to read the JSON string stored, you must parse it into a JavaScript object (or value, array, etc) , using the JSON.parse() method.
const xyzObjectRetrieved = JSON.parse(sessionStorage.get("xyzObject"));
// it should equal { name: "Juan" }
Source:
sessionStorage
JSON.stringify
JSON.parse

Is their is anyway to make json object schema fixed i.e always contains same key

Is their is anyway to make json object schema fixed so that whenever i will create new object it will show same fixed number of key. So that i can change the value for that key whenever required(As like setter and getter).
You're probably mixing json and javascript.
JSON is a data format for communication, it can be used to serailiaze javscript object to the server, but the server can serialize his own objects into JSON, wheter they come from nodeJS, Java, or whatever.
So let's assume you're talking about javascript, this is really easy let's say you want an object People with the field name, *firstname**, dateOfBirth. You can just create a class with his constructor like this :
// creating based fields
function People(){
this.name = null;
this.firstname = null;
this.dateOfBirth = null;
}
// instantiating objects :
var myPeople = new People();
But with that we can still do something like myPeople.foo = "bar". There is no way of preventing that in javascript. However you can make sure yourself that extrafield won't getserialized in JSON with something like this :
// adding method toJson to people
People.prototype.toJson = function(){
return JSON.stringify({name:this.name, firstname:this.firstname, dataOfBirth:this.dateOfBirth});
};
// using it
var myJsonString = myPeople.toJson();
So any extra field you could have need for some manipulation will be ignore on serializing to the serving. I advsied you that because you not only to filter you keys, but to translate some objects before serializing. For instance i never serialize Javascript Date object, i always take the Timestamp (from getTime() method).
I don't know if i understand your question clearly but here is what i came up with:
var schema = function(){
var a=0;
var b=2;
var getA = function(){
return a;
}
var setA = function(newValue){
a = newValue;
}
return {
getA:getA,
setA:setA
}
}
Then when you want a new instance you can do this.
var x = new schema();
x.setA(25);
x.getA();

HTML5 localstorage methods advantages?

I've been using localStorage and a question came to me:
Which is the advantage using setItem and getItem methods rather than:
SET ITEM : localStorage.myKey = "myValue";
GET ITEM : localStorgae.myKey --> returns "myValue"
Are they just helper methods then? Good practices?
Just about curiosity thanks.
HTML5 Storage is based on named key/value pairs. You store data based on a named key, then you can retrieve that data with the same key. The named key is a string. The data can be any type supported by JavaScript, including strings, Booleans, integers, or floats. However, the data is actually stored as a string. If you are storing and retrieving anything other than strings, you will need to use functions like parseInt() or parseFloat() to coerce your retrieved data into the expected JavaScript datatype.
interface Storage {
getter any getItem(in DOMString key);
setter creator void setItem(in DOMString key, in any data);
};
Calling setItem() with a named key that already exists will silently overwrite the previous value. Calling getItem() with a non-existent key will return null rather than throw an exception.
Like other JavaScript objects, you can treat the localStorage object as an associative array. Instead of using the getItem() and setItem() methods, you can simply use square brackets. For example, this snippet of code:
var foo = localStorage.getItem("bar");
// ...
localStorage.setItem("bar", foo);
…could be rewritten to use square bracket syntax instead:
var foo = localStorage["bar"];
// ...
localStorage["bar"] = foo;
Maybe this hope. :D
Reference: http://diveintohtml5.info/storage.html
set/getItem are better than property-access for the following reasons:
localStorage coerces all its input into strings, but you can overwrite the set/getItem methods to perform serialization and deserialization to support types other than strings:
var basicSetItem = localStorage.setItem;
localStorage.setItem = function(key, val) {
basicSetItem.call(localStorage, key, JSON.stringify(val));
}
var basicGetItem = localStorage.getItem;
localStorage.getItem = function(key) {
return JSON.parse(basicGetItem.call(localStorage, key));
}
You cannot achieve an equivalent effect for all storage property values using ECMAScript 5 APIs.
You cannot set the storage key length, and you cannot access the keys getItem, setItem, or removeItem without using function access:
localStoage.length = "foo"; // does not work
localStoage.setItem("length", "foo"); // works
var bar = localStoage.setItem; // gets the `setItem` function
var bar = localStorage.getItem("setItem"); // gets the value stored in the `setItem` key

Evaluate if Variable Name is equals to String

I have
var myArrayVariable1 = new Array();
var myStringVariable1 = 'myArrayVariable1';
var myStringVariable2 = 'myArrayVariable2';
Is there any way to figure out if one of the strings match the variables name? In case above, myStringVariable1.Value = myArrayVariable1.VariablesName
My conundrum:
I have around 100 objects that are unique to each user.
I need to update each object each minute
Each object is named as the database id; javascript would have to locate the object, delete it and then re-create it using new values (these are pulled via json)
So I need to locate the object (using the string that I have gotten from the json), then I need somehow call that object to delete it...
kind of stuck here.
In abstract I am looking for something like this:
foreach(object obj in allObjects){
if (obj.ActualName==="something"){
obj.Delete();
}
}
After some thinking, and no answer to my question, I am thinking about using some sort of dictionary (a hashmap equivalent) to track all the objects
if the variable is part of an object, you can traverse on it :
var obj {
myVar: 'hello'
};
for (var varName in obj) {
alert(varName + ' = ' + obj[varName]);
}

How to use JSON to re-build the Javascript Object?

I have an object like this:
var someObj = Class.create ({
initialize: function(objName){
this.objName = objName;
}
});
I can use
o = new someObj("objName");
to make an obj. I can use Object.toJSON(o) to change the o to become a JSON String,
but I want the JSON String convert back to someObj, so, I use eval() to pass the
JSON String to become an object, but the question is, it can become a JS Obj,
but the constructor of "o" is not someObj. How can I eval the JSON String by using
"someObj" as the constructor?
JSON strings cannot represent objects with member functions, so the only thing you will get out of a JSON string is raw data. Assuming the toJSON method results in a JSON string representing an object with all the non-function members of your class instance, you should be able to take the resulting object and attach the prototype to get all the functions back. For example, using jQuery's handy extend function:
var o = new someObj("objName");
var json = Object.toJSON(o);
var json_obj = eval(json);
$.extend(json_obj, someObj.prototype);
json_obj.someMethodDefinedOnsomeObj()
Depending on how the framework you are using to represent classes in JavaScript makes use of the prototypal object model, your milage may very with the above example. Also, using eval() creates a security hole, so if you do not trust where the JSON string is coming from, you should use a different de-serialization method. Just for full coverage, here is how I did it with raw prototypes:
function Animal(name){
this.name = name;
}
Animal.prototype.talk = function(){
console.log("My name is "+this.name);
}
var a = new Animal("Brendan Eich");
a.talk();
var json = '{name: "Tim Berners-Lee"}'
var b = eval(b);
$.extend(b, Animal.prototype);
b.talk();
In a firebug console this produces the output:
My name is Brendan Eich
My name is Tim Berners-Lee
See JSON revivers at http://json.org/js.html
var myObject = JSON.parse(myJSONtext, reviver);
The optional reviver parameter is a
function that will be called for every
key and value at every level of the
final result. Each value will be
replaced by the result of the reviver
function. This can be used to reform
generic objects into instances of
pseudoclasses, or to transform date
strings into Date objects.
you're using prototypejs right? i've always found that tricky and ended up just making my own initializer that read in an object that had been evaled or the json string itself.

Categories