I'm trying to get an array of data to insert into multiple columns in an sqlite database, I'v got it almost working with this:
function InsertData(dbData){
var valueArray = [], dataArray = [];
var values = Object.keys(dbData);
for(var key in values){
valueArray[valueArray.length] = values[key];
dataArray[dataArray.length] = dbData[values[key]];
}
console.log("INSERT INTO "+dbData.table+" ("+valueArray+") VALUES ("+JSON.stringify(dataArray)+")");
dbData.database.serialize(function(){
dbData.database.run("INSERT INTO "+dbData.table+" ("+valueArray+") VALUES ("+JSON.stringify(dataArray)+")");
});
}
My data is constructed as so:
//app.js
function EventData(title, value, other){
this.title = title;
this.value = value;
this.other = other;
}
EventData.prototype = new dbtools.DBData(usuevents, 'event');
var thisEventData = new EventData('newData', 4, 2);
//dbtools.js
DBData = function(database, table){
this.database = database;
this.table = table;
};
the console.log outputs INSERT INTO event (title,value,other) VALUES (["newData",4,2]) I just need the [] square brackets removed on (["newData",4,2]). How would I do this? Also if there is a better way to insert data into sqlite im open to suggestions. Thanks
JSON.stringify(dataArray)
will always return square brackets because dataArray
is of type array. Instead, you could stringify each element of your array, then join them separated by commas.
dataArray = dataArray.map(function(e){
return JSON.stringify(e);
});
dataString = dataArray.join(",");
Then
["newData",4,2]
becomes
"newData",4,2
Addendum: Please don't try to replace()
out the brackets manually because it could be that one day a bracket enters your array in a string. e.g. ["Please see ref[1]",4,2]
Thanks Drakes and S McCrohan for your answers. I found that .replace(/]|[[]/g, '')
appended to JSON.stringify(dataArray)
full line JSON.stringify(dataArray).replace(/]|[[]/g, '')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With