首页 > 解决方案 > 仅使用 chrome.storage.local.set 更新指定元素

问题描述

我在 chrome 本地存储中有一个数组,格式:

{"flights":
   [
      {"end":"2018-02-10","price":"476","start":"2018-02-01","tabId":1129367822},
      {"end":"2018-02-11","price":"493","start":"2018-02-01","tabId":1129367825},
      {"end":"2018-02-12","price":"468","start":"2018-02-01","tabId":1129367828}
   ]
}

现在我正在以这种方式更新所有数据:

function updateValue(index, item) {
    chrome.storage.local.get(['flights'], function (response) {
        response.flights[index] = item;
        chrome.storage.local.set({flights: response.flights});
    });
}

但是异步请求存在问题,因为我当时有几个请求。一些请求获取旧数据并将其再次保存在存储中......

我只想更新指定的元素(例如使用新数据的航班 [0]),但它不起作用......像这样的东西,但可行:

    chrome.storage.local.set({flights[0]: item});

有没有办法做到这一点?或者,也许您有一些建议以其他方式解决此问题。

非常感谢您的帮助

标签: javascriptgoogle-chrome-extension

解决方案


您可以将每个航班保存到一个单独的键中,并通过遍历所有存储来获取所有航班:

cosnt flightPrefix = 'flight_';    

function updateValue(index, item) {
    chrome.storage.local.set({flightPrefix + index: item});
}

function getFlights() {
    // Pass in null to get the entire contents of storage.
    chrome.storage.sync.get(null, function(items) {
        let flights = Object.keys(items).filter(key => key.beginsWith(flightPrefix));
        console.log(flights);
    });
}

推荐阅读