简体   繁体   English

"chrome.storage 从数组中删除特定项目"

[英]chrome.storage remove specific item from an array

This is the JSON stored in my chrome local storage这是存储在我的 chrome 本地存储中的 JSON

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

There is no magic syntax to delete only one element from an array that is stored in chrome.storage . 没有魔法语法只从存储在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 . 请参阅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. 否则你最终可能会删除错误的项目,因为在删除第一个项目后,后面的元素的索引会被删除,当你删除了两个项目时,它们会被两个项目关闭,等等。

Yes you can try this是的,你可以试试这个

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM