如何使用 Dexie.js 删除 key/value 内部值字段?

How to delete a key/value inside value field with Dexie.js?

我有一行值如下所示:

{
   "id": 1,
   "token": "abcd"
}

如何删除并保存没有 "token" 的值,使其变成这样?

{
   "id": 1
}

是否需要先获取对象,修改后再保存回来?

也许这会对你有所帮助:

function patch(db, id, delta) {
  return new Promise((resolve, reject) => {
    const tx = db.transaction('mystore', 'readwrite');
    tx.onerror = (event) => reject(event.target.error);
    tx.oncomplete = () => resolve();
    const store = tx.objectStore('mystore');
    const request = store.get(id);
    request.onsuccess = (event) => {
      const object = event.target.result;

      if (!object) {
        reject(new Error(`No matching object for ${id}`));
        return;
      }

      for (const prop in delta) {
         if (typeof delta[prop] === 'undefined') {
           delete object[prop];
         } else {
           object[prop] = delta[prop];
         }
      }

      store.put(object);
    };
  });
}

async function dostuff() {
  let db;
  const id = 1;
  const delta = {
    token: undefined
  };

  try {
    db = await connect();
    await patch(db, id, delta);
  } finally {
    if (db) {
      db.close();
    }
  }
}