Skip to content

Instantly share code, notes, and snippets.

@jesusalber1
Last active August 29, 2015 14:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jesusalber1/38919ff63f71d910dd37 to your computer and use it in GitHub Desktop.
Save jesusalber1/38919ff63f71d910dd37 to your computer and use it in GitHub Desktop.
LocalStorage manipulation
function setLocalStorage(key, value) {
if (typeof value == 'object') {
value = JSON.stringify(value);
}
localStorage.setItem(key, value);
}
function getLocalStorage(key) {
var value = localStorage.getItem(key);
/* if stored data is JSON -> parses it into an Object, else raw data (another type of variable stored as String). */
try {
value = JSON.parse(value);
} catch (error) {}
return value;
}
function deleteLocalStorage(key) {
localStorage.removeItem(key);
}
function clearLocalStorage() {
localStorage.clear();
}
/* Returns an object like: (Not an Array, Why? I want to identify later each item...)
{
itemName: itemValue,
itemName2: itemValue2,
...
}
*/
function getAllLocalStorage() {
var items = {};
for (var item in localStorage) {
items[item] = getLocalStorage(item);
}
return items;
}
/*
var me = {
name: 'Jesús Alberto',
github: 'JesusAlber1'
};
setLocalStorage('user', me);
getLocalStorage('user');
deleteLocalStorage('user');
setLocalStorage('user', me);
setLocalStorage('user2', 'JesusAlber1OnlyName');
getAllLocalStorage();
clearLocalStorage();
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment