Don't you just want to look at the first row of your 'data' element and enumerate through those keys (assuming all the rows are the same)?
for (var k in arrData[0]) {...
Don't you just want to look at the first row of your 'data' element and enumerate through those keys (assuming all the rows are the same)?
for (var k in arrData[0]) {...
In Javascript, and time you have an object with members that you can access via obj.member
, you can also access it as obj["member"]
. Objects in JavaScript are essentially just hash tables with the ability to call methods on them (which are also just entries in the hash table), and a prototype based inheritance system.
Anyhow, that means that you can use for ... in
to iterate over the properties in that hash table, and pull out the keys.
So, if I understand what you're trying to do correctly, you could just do something like this (note that the structure of this loop is somewhat different than the one in your question, as you're going to need one INSERT
statement for each row to insert, while your loop had the construction of the INSERT
statement outside of the loop over the data rows):
function populateTable(table, data) {
for (var k in data) {
var queryArgs = [];
var argArray = [];
var columns = [];
for (var col in data[k]) {
queryArgs.push('?');
columns.push(col);
argArray.push(data[k][col]);
}
var SQL = "INSERT INTO " + table + " (" + columns + ") VALUES " +
"(" + queryArgs + ");";
alert(SQL + " [" + argArray + "]")
}
}
I'm making some assumptions here, but try changing:
for (var k in arrData) {
strVal = "?,";
arrVal.push(arrData[k]. ~~ KEY VALUE NAME ~~ )
}
var strSQL = "INSERT INTO " + table + " (" + strCol + ") ";
strSQL += "VALUES (" + strVal.lastIndexOf(",") + ");";
to:
for (var i =0; i < arrColumns.length; ++i) strVal += ',?';
for (var k in arrData)
{
arrVal[k] = [];
for (var i in arrColumns)
arrVal[k].push (arrData[k][arrColumns[i]]);
}
var strSQL = "INSERT INTO " + table + " (" + strCol + ") ";
strSQL += "VALUES (" + strVal.substr(1) + ");";
If I'm correct in thinking that transaction.executeSql(strSQL, arrVal, null, dbController.errorHandler);
accepts multiple records, then this should work fine. Otherwise, call
transaction.executeSql(strSQL, arrVal[0], null, dbController.errorHandler);
instead