简体   繁体   中英

update only specified element with chrome.storage.local.set

I have an array in chrome local storage, format:

{"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}
   ]
}

Now I'm updating all data this way:

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

But there is problem with async requests, because I have several request at the time. Some requests get old data and save it again in storage...

I want to update only specified element (for example flights[0] with new data), but it doesn't work... Something like this, but workable:

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

Is there any way to do this? Or maybe you have some advices to resolve this issue other way.

many thanks for any help

You can save each flight into a separate key and get all flights by traversing all storage:

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

Based on terales ' answer (that code has some errors). I make it this way:

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

Thanks for help!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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