Reputation: 32726
I'm writing a localStorage wrapper to make inserting and retrieving data easier when needing it to do more robust queries.
My script is here: https://github.com/OscarGodson/storageLocker
A user of my script asked me how he could save a Date and i told him the proper procedure (save new Date().getTime()
to the JSON and revive it with something like new Date(json.time)
but he was trying to do hisStorage.save({'the_date':new Date()})
, but to his surprise when he went to get the data it'd be malformed.
So, my question is, how can I catch inserts like this and other objects (maybe events?), convert them for the users to be stored in the JSON and also retrieved properly? I've been working on it all day and i can't figure out how to check for certain types of objects and convert accordingly via some switch case.
The save and retrieve part of my script looks like this:
Saving Data:
storageLocker.prototype.save = function(value){
var json = JSON.parse(localStorage.getItem(this.catalog));
if(json == null){json = {};}
for(var key in value){
if(value.hasOwnProperty(key)){
json[key] = value[key];
}
}
localStorage.setItem(this.catalog,JSON.stringify(json));
return this;
}
Getting Data:
storageLocker.prototype.get = function(value){
json = JSON.parse(localStorage.getItem(this.catalog));
if(json == null){json = {};}
if(value){
if(typeof json[value] !== 'undefined'){
return json[value];
}
else{
//Makes it so you can check with myStorage.get('thisWontExist').length
//and it will return 0 and typeof will return object.
return new Object('');
}
}
else{
return json;
}
};
Upvotes: 0
Views: 130
Reputation: 38046
Use the instanceof
operator to check whether the property is an instance of Date
:
if (value[key] instanceof Date) {
//serialize in some way
...
}else{
json[key] = value[key];
}
The problem is; in the getter, how are you going to know which values need to be revived again? You'll have to rely on some string format and accept that if the user saves a string in this format, then it will be revived as a date.
Upvotes: 2