假设您已将 CSV 解析为数组数组,即 var data = [["timestamp", ["temp1", "temp2", "temp3"], ["timestamp2", ["temp4", "temp5 ", "temp6"], 等等..];
然后我将列映射到行名:
columns = ["timestamp", "temperature"];
然后用它们构造一个简单的字典:
var objectStore = db.transaction("temperatures", "readwrite").objectStore("temperatures");
for (var i = 0; i < data.length; i++) {
var data = {};
var row = data[i];
for (var j = 0; j < row.length; j++) {
data[columns[j]] = row[j];
}
objectStore.put(data, i);
}
这样您就可以使用objectStore.get(rownumber)
但为了更加 NoSQLish,我将其中一列(比如“时间戳”)作为对象的键路径,并使用 multiEntry 索引温度数组的所有子值。以这种方式创建它:
db.createObjectStore("temperatures", {keyPath: "timestamp"});
db.createIndex("temp", "temperature", {"multiEntry": true});
然后当你放的时候,不要费心使用密钥:
objectStore.put(data);
然后你可以根据它来检索东西:
objectStore.get("2012-04-05");
但真正很棒的是,现在你有了一个逆向的温度索引,让你可以说“给我所有温度在 20 到 30 度之间的记录”:
objectStore.index("temp").openCursor(IDBKeyRange.bound(20, 30)).onsuccess = function(e) {
var cursor = e.target.result;
if (cursor) {
cursor.continue();
console.log("Found record: ", cursor.value);
}
}
您只需要小心使 objectstore 的键路径指向唯一可识别的列。