代码之家  ›  专栏  ›  技术社区  ›  MrSmile cashews

仅使用chrome.storage.local.set更新指定元素

  •  0
  • MrSmile cashews  · 技术社区  · 7 年前

    我有一个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});
    

    非常感谢你的帮助

    2 回复  |  直到 7 年前
        1
  •  1
  •   terales    7 年前

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

    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);
        });
    }
    
        2
  •  1
  •   MrSmile cashews    7 年前

    基于 特莱尔斯 我这样说:

    function parseFlight(result) {
        let flightsArray = [];
        Object.keys(result).forEach(function (key) {
            if (key.includes('flight')) {
                let index = key.replace('flight_', '');
                flightsArray[index] = result[key];
            }
        });
        return flightsArray;
    }
    
    function updateValue(index, item) {
        let flightPrefix = 'flight_';
        let obj = {};
        obj[flightPrefix + index] = item;
        chrome.storage.local.set(obj);
    }
    
    chrome.storage.local.get(null, function (result) {
        let flights = parseFlight(result);
    });
    

    谢谢你的帮助!