I am working with the local storage and I am struck in a problem.
I want to store the values for the key like this. The values are added dynamically and the should be separated by "," . I should retrieve them by comparing the value
here is my view
key value
user1 a,b,c,d,e....
The values in the value field should be added dynamically. say I have fields username and add friend. the username should take the position key and add friend(dynamic) should take the value position.
first iteration:
username _a________
add friend _hello_______
localstorage : key value
a hello
second iteration:
username _____a___
add friend : __stact___
local storage : key value
a hello , stact
third iteration :
username _____a___
add friend : __hi___
local storage : key value
a hello , stact,hi
If i want to delete stact i have to write localStorage.removeKey(a[1])
.
Please help me out as I am a newbie to this stuff I have used one of the answers below to my code but It didn't work. instead it is throwing error I have tried the following
var ls = (function () {
var _key = function (username) {
return username;
},
_saveFriends = function (username, friends) {
localStorage.setItem(ls._key(username), JSON.stringify(friends));
};
function getFriends(username) {
return JSON.parse(localStorage.getItem(ls._key(username)) || '[]');
}
return {
getFriends: getFriends,
addFriend: function (username, friend) {
var friends = getFriends(username);
friends.push(friend);
_saveFriends(friends);
},
removeFriend: function (username, friend) {
var friends = getFriends(username);
var index = friends.indexOf(friend);
if (index >= 0) {
friends.splice(index, 1);
}
_saveFriends(friends);
}
};
})();
function main()
{
ls.addFriend('revanth','aastha');
ls.addFriend('revanth','pobala');
ls.getFriends('revanth');
Here is the error Uncaught TypeError: undefined is not a function and the error is in this line return JSON.parse(localStorage.getItem(ls._key(username)));