1

I am pulling data from my remote database and get this JSON data:

{"list1":{"id":1, "item":"testobj1"},"list2":{"id":2, "item":"testobj2"},"list3":{"id":3, 
"item":"testobj3"},"list4":{"id":4, "item":"testobj4"},"list5":{"id":5, "item":"testobj5"}}

I can now loop through the objects in the data and display a list of objects on my screen. It works fine:

var d = JSON.parse(hr.responseText);
databox.innerHTML = "";
for (var o in d) {
    if (d[o].item) {
        databox.innerHTML += '<p>' +     d[o].item + '</p>' + '<hr>';

    }
}

Now however, I would like to insert this data into my Sqlite database. I am not quite sure how I can tell the loop that 'd[o].id' and 'd[o].item' are the items I would like insert into my db.

db.transaction(function(tx) {
    var sql = "INSERT OR REPLACE INTO testTable (id, item) " + "VALUES
    (?, ?)";
    log('Inserting or Updating in local database:');
    var d = JSON.parse(hr.responseText);
    var id = d[o].id;
    var item = d[o].item;
    for (var i = 0; i < d.length; i++) {
        log(d[o].id + ' ' + d[o].item);
        var params = [d[o].id, d[o].item];
        tx.executeSql(sql, params);
    }
    log('Synchronization complete (' + d + ' items synchronized)');
}, this.txErrorHandler, function(tx) {
    callback();
});

I hope somebody can take a look at this loop and tell me where did I go wrong. Many thanks in advance!

1
  • Is d an array or an object? If it's an object, your iteration as it is will not work (d.length is undefined). Commented May 16, 2014 at 23:47

1 Answer 1

1

You're iterating over d as if it's an array rather than an object. Something like this is probably what you're looking for:

var d = JSON.parse(hr.responseText);
for (var o in d) {
    var params = [d[o].id, d[o].item];
    tx.executeSql(sql, params);
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks a lot for the hint! d is an object. I didn't get it to run yet but do you think it'd be easier to insert data from an array?
Easier? Not necessarily, though it'd make more sense in your case. Especially if the order of your inner objects matter (for...in won't always iterate over your properties in the order which they're declared)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.