I am trying to transfer entries from a mysql database (delivered by PHP via JSON) to a localforage db. The records listed under transactions are numbered with an id property (ascending from 1 to about 400 in the JSON string). My goal is to use these ids as keys for localforage. However the result is like shown in the screenshot from DevTools below.
var tmp, id;
var json = JSON.parse(data); // data is the JSON encoded string returned from server
for(var i = 0; i < json.transactions.length; i++){
tmp = json.transactions[i];
id = String(tmp.id);
console.log(typeof id);
delete tmp.id;
transactions.setItem(id, tmp).then(function (value) {
//console.log(value);
}).catch(function (err) {
console.log(err);
});
}
resulting database in localforage in DevTools (Screenshot)
How can I get localforage to use the correct ids (1, 2, 3, 4 ... 400 etc.) instead of these converted keys (that seem to descend from another number system)?
The keys are strings, and so collate as "1" < "10" < "100" < "11" < "2". Presumably you want the order to be 1, 2, 10, 11, 100 ?
The underlying data store (IndexedDB) supports keys which are numbers and collate, so you could drop localforage and use IndexedDB directly.
Alternately, left-pad the strings:
id = ("00000000" + String(tmp.id)).substr(-8);... which would give you: "00000001" < "00000002" < "00000010" < "00000011" < "00000100".