如何在 indexedDB 中存储 JSON 对象?

Rub*_*ira 6 javascript json indexeddb

我的返回 json 文件如下所示:

var data = [{"col1":"value1","col2":"value1","col3":"value1"},{"col1":"value2","col2":"value2","col3":"value2"},{"col1":"value3","col2":"value3","col3":"value3"}];
Run Code Online (Sandbox Code Playgroud)

没有 JSON.stringify 数据看起来像这样:

[对象对象],[对象对象],[对象对象]

但有了它,result.length 不是 5,而是字符串的总字符数,这样我就不能循环了

var result = JSON.stringify(data);
for(i=0; i<result.length; i++){
var transaction = db.transaction([STORE], IDBTransaction.READ_WRITE);
var put = transaction.objectStore(STORE).put(result);
};   
Run Code Online (Sandbox Code Playgroud)

Mar*_*.io 5

var data = [{"col1":"value1","col2":"value1","col3":"value1"},{"col1":"value2","col2":"value2","col3":"value2"},{"col1":"value3","col2":"value3","col3":"value3"}];
Run Code Online (Sandbox Code Playgroud)

如果您尝试存储每个对象,那么不要对其进行字符串化或任何其他操作,它已经处于完美的形式。更改for()循环以循环访问数据对象。

出于性能原因, Kristof Degrave有一个很好的观点,将它们放在实际的 for 循环之外。

    var transaction = db.transaction([STORE], IDBTransaction.READ_WRITE); 
    var objstore = transaction.objectStore(STORE); 

    for (i = 0; i < data.length; i++) { 
        objstore.put(data[i]);
    } 
Run Code Online (Sandbox Code Playgroud)

  • 现在,您正在为要存储的每个对象创建一个事务和一个对象存储对象。如果您在 for 循环之外执行此操作,您将创建一次并在一个事务中执行所有 put 操作。这样做: var transaction = db.transaction([STORE], IDBTransaction.READ_WRITE); var objstore = transaction.objectStore(STORE); for(i = 0; i &lt; data.length; i++){ objstore.put(data[i]); } (2认同)