Alex Coroza
Alex Coroza

Reputation: 1757

chrome.storage remove specific item from an array

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!');
});

Upvotes: 8

Views: 8299

Answers (2)

MD SHAYON
MD SHAYON

Reputation: 8051

Yes you can try this

chrome.storage.sync.remove("token");

see documentation

Upvotes: 3

Rob W
Rob W

Reputation: 349052

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.

Upvotes: 7

Related Questions