如何在IndexedDB中循环存储键

时间:2018-04-12 08:03:27

标签: vue.js localforage

我正在使用localForage for IndexedDB,我需要遍历存储密钥,但不是全部。我只需要遍历以“field-”开头的键。 例如: field-1,field-2,field-3,...

2 个答案:

答案 0 :(得分:0)

根据我的发现,无法获取存储中的所有可用密钥。但是,由于您在某个时刻设置了localforage的所有键,也许您可​​以单独存储这些键。

// storing a new key, could be wrapped inside of a function and included anywhere you update localforage
const newKey = "abc"
const availableKeys = localforage.getItem('keys')
  .then((keys = []) => { // localforage will return undefined if the key does not already exists, this will set it do an empty array by default
    // check here if key is already in keys (using Array.find)
    // push the key that you want to add
    keys.push(newKey)
    // now update the new keys array in localforage
    localforage.setItem('keys', keys)
  })

这样做就可以使用它来迭代所有可用的密钥

localforage.getItem('keys')
  .then((keys = []) => {
    keys.forEach(key => {
      // you could not check if the key has you pattern
      if (key.indexOf("field-") > -1) // key has "field-", now do something
    })
  })

因为您不想遍历所有键,所以您可以使用过滤函数再次单独存储子集

localforage.getItem('keys')
  .then((keys = []) => {
    // fiter all keys that match your pattern
    const filteredKeys = keys.filter(key => key.indexOf("field-") > -1)
    // store filtered keys in localeforage
    localforage.setItem("filteredKeys", filteredKeys)
  })

答案 1 :(得分:0)

localforage.iterate(function(value, key, iterationNumber) {
  if (key.indexOf("field-") > -1) {
    // do something
  }
});
相关问题