LocalStorage - Remove item by value and not key?

2019-08-01 05:34发布

问题:

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.

回答1:

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));


回答2:

LocalStorage comes with a length so you know how many values are being stored and a method key which lets you find a key at an index.

function removeLocalStorageValues(target) {
    let i = localStorage.length;
    while (i-- > 0) {
        let key = localStorage.key(i);
        if (localStorage.getItem(key) === target) {
            localStorage.removeItem(key);
        }
    }
}