clearing objects from localstorage - javascript

with localstorage i have a load of unspecified items saved with dynamic names using a data namespace like so:
localStorage["myAppName.settings.whatever"] = something.whatever;
//and this:
localStorage["myAppName.data."+dynObj.name] = dynObj.data;
I want to keep the settings but not the data. However I won't ever know what all of the names inside of my data object are so I cannot clear them individually. I need to clear these each time my app is loaded but I must keep the settings so
localstorage.clear() is not an option.
I have tried:
localstorage.removeItem("myAppName.data")
but no dice.
Anyone have any thoughts on how to clear dynamically named portions of localstorage?

You can loop through the keys in the localStorage and target them with a reg exp:
Object.keys(localStorage)
.forEach(function(key){
if (/^(myAppName.data.)/.test(key)) {
localStorage.removeItem(key);
}
});
Here's a similar question: HTML5 Localstorage & jQuery: Delete localstorage keys starting with a certain word

try something like
var i = localStorage.length, key;
while (i--) {
key = localStorage.key(i);
if (key.slice(0, 19) !== "myAppName.settings.") {
localStorage.remove(key);
}
}

Tried something like this?
// Select current settings
var settings = localStorage["myAppName.settings"] || {};
// Clear localStorage
localStorage.clear();
// Add settings to localStorage
localStorage["myAppName.settings"] = settings;

Assuming a this.namespace present (in my case 'session') and the underscore library:
_.each(_.keys(localStorage), function(key) {
if (RegExp("^" + this.namespace + "\\.").test(key)) {
return localStorage.removeItem(key);
}
});
And with CoffeeScript:
_.each _.keys(localStorage), (key) ->
if ///^#{#namespace}\.///.test(key)
localStorage.removeItem(key)

Related

How to retrieve a specific object from a JSON value stored in sessionStorage?

I have this stored in the session:
What I'm looking to do is assign each object in the JSON as a variable so I can add them to the DOM appropriately.
This works but prints everything out:
if (sessionStorage.getItem('wc_fragments_aaf6a2e5b971cb51d59e8f3eae9b34c9') != null) {
$(sessionStorage.getItem('wc_fragments_aaf6a2e5b971cb51d59e8f3eae9b34c9')).appendTo('.div');
}
What I'd like is something like this, but it doesn't work:
var div1 = $(JSON.parse(sessionStorage.getItem('wc_fragments_aaf6a2e5b971cb51d59e8f3eae9b34c9', 'a.cart-contents')));
var div2 = $(JSON.parse(sessionStorage.getItem('wc_fragments_aaf6a2e5b971cb51d59e8f3eae9b34c9', 'a.footer-cart-contents')));
var div3 = $(JSON.parse(sessionStorage.getItem('wc_fragments_aaf6a2e5b971cb51d59e8f3eae9b34c9', 'div.widget_shopping_cart_content')));
Any help would be greatly appreciated. Thank you!
Getting the same value from the storage several times is not a good idea. In addition, you need better names for your variables.
var json = sessionStorage.getItem('wc_fragments_aaf6a2e5b971cb51d59e8f3eae9b34c9');
if (json) {
var data = JSON.parse(json);
if (data) {
var cart_link = $(data['a.cart-contents']),
footer_link = $(data['a.footer-cart-contents']),
widget_div = $(data['div.widget_shopping_cart_content']);
}
}
So it appears you have set selectors as keys of the object so you could iterate those keys to get each selector.
The propose of those selector keys is not 100% clear. I am assuming that those selectors are the elements you want to insert the html strings into and that $() means you are using jQuery
if (sessionStorage.getItem('wc_fragments_aaf6a2e5b971cb51d59e8f3eae9b34c9') != null) {
var data = JSON.parse(sessionStorage.getItem('wc_fragments_aaf6a2e5b971cb51d59e8f3eae9b34c9');
$.each(data, function(selector, htmlString){
$(selector).append(htmlString)
});
}

Jquery and php wishlist - how to retrieve data?

I have a script that randomly shows divs when you press a button. I would like to make a wish list page in order for people to keep track of what they liked.
I have set a session and a cookie for a day. this is my script and it doesn't work but I'm not sure why... Thanks for all your help.
$(".places").hide();
$("#button").click(function(){
"use strict";
var randomNumber = Math.floor(Math.random()*45);
var selectedDiv = "#place" + randomNumber;
$('.places').hide().filter(selectedDiv).show();
$(".wishlistbutton").click(localStorage.setItem(selectedDiv,JSON.stringify(wishlist)));
});
var wishlistkey = "wishlist";
var wishlist = localStorage.getItem(wishlistkey);
if($.isEmptyObject(wishlist)){
wishlist = new Array()
} else {
wishlist = JSON.parse(wishlist);
}
The $.isEmptyObject method does not work as you expected since you are providing a string as the argument(expected argument type is a plain JS object), actually which is unnecessary in your code.
var wishlist = localStorage.getItem(wishlistkey);
if(!wishlist){
wishlist = new Array()}
else {
wishlist = JSON.parse(wishlist);
}
Although you need to store the JSON string in localStorage with key as wishlist instead of the div id.
localStorage.setItem('wishlist', JSON.stringify(wishlist))
It looks like you're calling localStorage setItem and passing in a key, that is the name of the div (selectedDiv), but then you're trying to getItem on a key named "wishlist" Try setting item in storage like this
$(".wishlistbutton").click(localStorage.setItem("wishlist", JSON.stringify(wishlist))); });

Redis key is not creating properly

I am new to Redis and am trying to hmset some values by generating my own keys to store and access it. But for some reason, key is not being created properly and the data's are overwritten. Below is my code for it,
locations.forEach(function(location) {
var key = location.id;
console.log(key); // all keys are correct
client.hmset("locations", { key: location }); // using redis-jsonify
});
The data am getting is only one of the whole response since the key is actually saved as key itself.
For example:
I tried using client.incr('id', function(err, id) {}); but same problem.
Need help with this. Thanks in advance.
From the Redis HMSET doc:
Sets the specified fields to their respective values in the hash
stored at key. This command overwrites any existing fields in the
hash. If key does not exist, a new key holding a hash is created.
HMSET is used to set all the values at once.
If you want to set one hash field at a time, use HSET:
locations.forEach(function(location) {
var key = location.id;
client.hset("locations", key, location); // or `JSON.stringify(location)` if redis-jsonify doesn't work as expected
});
Closures to resuce
for (var i = 0; i < locations.length; i++) {
(function(i) {
console.log('locations: ' + location[i]);
client.hmset("locations", { i: location[i] });
})(i);
}

Javascript search if LocalStorage variable exists

I am programming a chat system. I always make a Localstorage variable when a new chat is opened. Created like this:
localStorage.setItem("chat_"+varemail, data);
Now i want to check how many of them I have so something like:
"chat_"+... count.
How can I do this?
You'd grab the array of keys of the localStorage object, and use Array.filter to grab only the items starting with "chat_":
var length = Object.keys(localStorage).filter(function(key) {
return /^chat_.+/.test(key);
}).length;
Here's a JSFiddle
Try something like this, loop through all items in localStorage and match against your pattern
function getChatCount(){
var chatCount = 0;
for(item in localStorage){
if(item.indexOf('chat_') > -1) chatCount++;
}
return chatCount;
}
Local storage is based on key, value pairs. AFAIK, you wouldn't be able to retrieve all values with a certain prefix.
One potential solution would be to store an object that contains these. Based on your needs you could store the objects in an array or object and then retrieve the entire set and find the count.
For example:
var chats = { count: 0 };
chats["chat_"+varemail] = data;
chats.count += 1;
localStorage.setItem('chats', data);
Then if you want a count, you would retrieve the object:
var chats = localStorage.getItem('chats');
//chats.count would give you the count.
Although, this would mean you have to manually maintain the count variable when adding or removing data. If you don't need the indexing ability, you could add the chats to an array and store that.
EDIT: It is possible to find properties with a certain prefix, as seen in an answer to this question.
I would offer to convert to localStorage.setItem("chat", JSON.stringify(stack)), where stack is an array of chat objects. This way, you have access to an array of chats which you can count, search within, etc.
Something like:
var chatStore =
{
Count: function () {
var stack = JSON.parse(localStorage.getItem("chats"));
if (!stack)
return 0;
return stack.length;
},
Peek: function () {
var stack = JSON.parse(localStorage.getItem("chats"));
if (!stack)
stack = [];
if (stack.length > 0)
return stack.pop();
},
Push: function (token) {
var stack = JSON.parse(localStorage.getItem("chats"));
if (!stack)
stack = [];
stack.push(token);
localStorage.setItem("chats", JSON.stringify(stack));
},
// more methods to you might wish to implement: search, insert, etc.
}
// usage:
chatStore.Push(chatObject); // sets the last chat
chatStore.Peek(); // gets the last chat

Issue with JSON stringify?

/* Helper function to clean up any current data we have stored */
function insertSerializedData(ids, type) {
// Get anything in the current field
current_data = $('#changes').val();
if (!current_data) {
var data = new Array();
data[type] = ids;
$('#changes').val(JSON.stringify(data));
} else {
var data = JSON.parse($('#changes').val());
data[type] = ids;
$('#changes').val(JSON.stringify(data));
}
console.log($('#changes').val());
}
I am using the following function to either add data to a current JSON object or create a new JSON object all together to be used in PHP later. Is the stringify() method only for FF? I am using google chrome and I am being given an empty object when using the conosole.log() function...
Also what happens if you try to store two values with the same key? I assume it will overwrite...so I should add a random math number at the end array in order to keep duplicates from showing up?
Thanks :)
These lines may cause problems:
var data = new Array();
data[type] = ids;
... because arrays in JavaScript are not quite like arrays in PHP. I suppose what you meant is better expressed by...
var data = {};
data[type] = ids;
Besides, current_data seems to be local to this function, therefore it also should be declared as local with var. Don't see any other problems... except that similar functionality is already implemented in jQuery .data() method.
UPDATE: here's jsFiddle to play with. ) From what I've tried looks like the array-object mismatch is what actually caused that Chrome behavior.
I reformatted it a bit, but and this seems to work. It will set the "value" attribute of the #changes element to a JSON string. I assume that the type argument is supposed to be the index of the array which you're trying to assign?
function insertSerializedData(ids, type) {
var changes = jQuery('#changes'), arr, val = changes.val();
if (!val) {
arr = [];
arr[type] = ids;
changes.val(JSON.stringify(arr));
} else {
arr = JSON.parse(val);
arr[type] = ids;
changes.val(JSON.stringify(arr));
}
console.log(changes);
}

Categories

Resources