my return json file looks like this:
var data = [{"col1":"value1","col2":"value1","col3":"value1"},{"col1":"value2","col2":"value2","col3":"value2"},{"col1":"value3","col2":"value3","col3":"value3"}];
without JSON.stringify data looks like this:
[object Object],[object Object],[object Object]
but with it the result.length is not 5 but the total number of characters of the string and that way I cant do the loop
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);
};
my return json file looks like this:
var data = [{"col1":"value1","col2":"value1","col3":"value1"},{"col1":"value2","col2":"value2","col3":"value2"},{"col1":"value3","col2":"value3","col3":"value3"}];
without JSON.stringify data looks like this:
[object Object],[object Object],[object Object]
but with it the result.length is not 5 but the total number of characters of the string and that way I cant do the loop
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);
};
Share
Improve this question
edited May 25, 2014 at 3:55
Josh
18.7k7 gold badges54 silver badges72 bronze badges
asked Sep 26, 2012 at 17:33
Ruben TeixeiraRuben Teixeira
5742 gold badges8 silver badges17 bronze badges
1
- Don't stringify and In line 4 put(result[i]) – G Herbowicz Commented Feb 4, 2022 at 6:09
2 Answers
Reset to default 5var data = [{"col1":"value1","col2":"value1","col3":"value1"},{"col1":"value2","col2":"value2","col3":"value2"},{"col1":"value3","col2":"value3","col3":"value3"}];
If you are trying to store each OBJECT, then don't stringify it or anything, it is already in perfect form. Change your for()
loop to loop through the data objects.
Kristof Degrave had a good point to put these outside of the actual for loop for performance reasons.
var transaction = db.transaction([STORE], IDBTransaction.READ_WRITE);
var objstore = transaction.objectStore(STORE);
for (i = 0; i < data.length; i++) {
objstore.put(data[i]);
}
For new visitors, suggesting a tad of modification: IDBTransaction.READ_WRITE has been deprecated so use "readwrite" instead.
Resource: https://developer.mozilla/en-US/docs/Web/API/IndexedDB_API/Using_IndexedDB Reference:
Older experimental implementations use the deprecated constant IDBTransaction.READ_WRITE instead of "readwrite".
Also, to reduce the loc (which I mostly prefer), use:
var objstore = db.transaction([STORE], "readwrite").objectStore(STORE);
for (i = 0; i < data.length; i++) {
objstore.put(data[i]);
}