DionysoSong DionysoSong - 3 months ago 21
Javascript Question

LocalStorage - Remove item by value and not key?

Ok so I have a JSON like this stocked in LocalStorage :

[{"pseudo":"Lucia","id":2},{"pseudo":"Romain","id":1}]


I searched how I can remove one item and I only find this :

storage.removeItem(keyName);


But, correct me if I am wrong, if I use this will remove all the value with keyName "pseudo" if I do storage.removeItem(pseudo);

How can I only remove
{"pseudo":"Romain","id":1}
from the json and keep
{"pseudo":"Lucia","id":2}
?

Thank you.

UPDATE something like this ?

var ami_json = window.localStorage.getItem("info");
var amiNotifies = JSON.parse(ami_json);

var getIndexOf = function (psdu) {
for (var i = 0; i < amiNotifies.length; i++) {
if (amiNotifies[i].pseudo === psdu) {
return i;
}
}

return -1;
};

if (amiNotifies.length > 0) {
var index = getIndexOf(pseudo);
if (index > -1) {
//so already exists. now remove it.
var storedName = JSON.parse(localStorage.getItem(pseudo));

var indexToRemove = index;

//remove item selected, second parameter is the number of items to delete
amiNotifies.slice(indexToRemove, 1);

// Put the object into storage
localStorage.setItem('pseudo', JSON.stringify(amiNotifies));
console.log(amiNotifies);
console.log(angular.toJson(amiNotifies));

Array.prototype.splice.call(amiNotifies, index, 1);
$scope.isChecked[id] = "fa fa-circle-o pull-right";
}
}

Answer

localstorage only supports string values, so you need to parse data.

    var storedNames = JSON.parse(localStorage.getItem("keyName"));

    // here you need to make a loop to find the index of item to delete
    var indexToRemove = 1;

    //remove item selected, second parameter is the number of items to delete 
    storedNames.slice(indexToRemove, 1);

   // Put the object into storage
   localStorage.setItem('keyName', JSON.stringify(storedNames));