Reputation: 2485
I don't know if I'm over complicating things.. but I'm trying to have an ability to remove an json object in local storage. There is only one localstorage item holding all the data.
I get no errors but when I go back to the page the item is still there.
Console Logged Json
{
"cities": [
{
"id": 0,
"storename": "test",
"notes": "test",
"rejected": "on",
"offer": "test"
},
{
"id": 1,
"storename": "test2",
"notes": "test2",
"rejected": "on",
"offer": "test2"
}
]
}
Jquery
$('.deleteButton').click(function(){
var id = $(this).data('centreid');
$(this).remove();
localStorage.clear();
console.log(JsonData);
$.each($.parseJSON(JsonData), function(idx, cities) {
$.each(cities, function(idx, obj){
delete id[id];
});
});
var Count = 0;
localStorage.setItem(Count, JsonData);
JsonData = localStorage.getItem(Count);
Upvotes: 1
Views: 2264
Reputation: 14535
The problem is that your $.parseJSON(JsonData)
returns parsed object, than you change this object, but didn't store anywhere, so it goes. You need to store parsed object to variable, modify and than call SetItem with this object. Working example:
$('.deleteButton').click(function(){
var id = $(this).data('centreid');
$(this).remove();
localStorage.clear();
console.log(JsonData);
var data = JSON.parse(JsonData),
indexToRemove = null;
$.each(data['cities'], function(idx, obj){
if (obj['id'] == id) {
indexToRemove = idx;
return false;
}
});
if (indexToRemove !== null) {
data['cities'].splice(indexToRemove, 1);
}
var Count = 0;
localStorage.setItem(Count, JSON.stringify(data));
JsonData = localStorage.getItem(Count);
Upvotes: 1
Reputation: 1238
line is correct?
delete id[id];
you is not by setting the variable again only this object moving in
var data = $.parseJSON(JsonData);
for(var prop in data){
for(var i=0; i< data[prop].length; i++){
if(data[prop][i].id == id){
data[prop].splice(i, 1);
break;
}
}
}
JsonData = json.stringify(data);
Upvotes: 0
Reputation: 7553
You're deleting the object from the parsed JSON string, using $.parseJSON
. However, when setting the item into local storage, you're using the original string again.
To solve - overwrite the string with the revised JSON object.
Upvotes: 0