Pregunta

This is the JSON stored in my chrome local storage

{"users":[
    {"password":"123","userName":"alex"},
    {"password":"234","userName":"dena"},
    {"password":"343","userName":"jovit"}
]}

Is it possible to remove a specific item in "users" ? I tried to this code but no luck

chrome.storage.local.remove('users[0]', function(){
    alert('Item deleted!');
});
¿Fue útil?

Solución

There is no magic syntax to delete only one element from an array that is stored in chrome.storage. In order to delete an item from the array, you has to retrieve the stored array, throw away the unwanted items (or equivalently, keep only the items that you want to keep), then save the array again:

chrome.storage.local.get({users: []}, function(items) {
    // Remove one item at index 0
    items.users.splice(0, 1);
    chrome.storage.set(items, function() {
        alert('Item deleted!');
    });
});

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice.

Note that if you want to delete one or more items whose value satisfies a certain condition, you have to walk the array in reverse order. Otherwise you may end up removing the wrong items since the indices of the later elements are off by one after removing the first item, off by two when you've removed two items, etc.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top