14

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

Devcon
  • 767
  • 2
  • 8
  • 23

3 Answers3

32

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]

Drakes
  • 23,254
  • 3
  • 51
  • 94
6

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, '')

Devcon
  • 767
  • 2
  • 8
  • 23
  • 2
    It could be possible that at some point in the future a bracket could creep into one of your `dataArray` entries. It's been known to happen – Drakes Apr 20 '15 at 00:04
  • 4
    Right. If you want to take the regex approach (which is also valid), try `/^\[|]$/g`, to only match at the beginning and end of the string and avoid altering any interior elements. – S McCrohan Apr 20 '15 at 00:13
5

Drake's answer would be my personal choice, because the code clearly expresses the intent. But to show an alternative:

var strung = JSON.stringify(dataArray);
console.log(strung.substring(1,strung.length-1));
S McCrohan
  • 6,663
  • 1
  • 30
  • 39