javascript - 仅使用 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});
有没有办法做到这一点?或者,也许您有一些建议以其他方式解决此问题。
非常感谢您的帮助
解决方案
您可以将每个航班保存到一个单独的键中,并通过遍历所有存储来获取所有航班:
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);
});
}
推荐阅读
- flutter - 无法在 Flutter 中滚动 ListView
- blogdown - blogdown:new_site() 和 New Project > website using blogdown 都出错
- java - 为什么我的应用程序在某些设备上崩溃?
- angular - Spring Boot JWT Cors 不适用于 Angular 8
- python-click - 以编程方式生成 Click-Python 选项
- mysql - 如何创建数据库设计以保存具有特定任务的特定设备的记录?
- regex - Vim:在数字和左括号之间添加 * 符号
- c++ - STD::Tuple 实现 C++
- python - 与 Python 的 TCP/IP 连接,.recv() 没有任何回报
- python - 从 Python 程序中的 Pyspark SQL 数据框中检索值