Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterating through fields in a Nodejs MySQL result set

I'm a relative node newbie (old school programmer)

I have working code to grab a result set and parse through rows. I'm using felx's node-mysql driver. It's not hard to specifically print out columns.

connection.query('SELECT * FROM Company', function(err, rows, fields) {
    if (err) throw err;

    for (var i = 0; i < rows.length; i++) {
        result = "";
       result = result + ('| ' + rows[i].name + ' | ' + rows[i].address_zip);
        theEmail = theEmail + result + "<BR>";
}

What I really want to do is loop through fields without having to name them ... my gut tells me it would be rows[i].[j] ... or something like that.

Is this possible?

like image 280
Barry Smith Avatar asked Dec 18 '22 19:12

Barry Smith


2 Answers

If I understand your question correctly (you don't want to have to rows[i].name every time)

You can use For...of assuming all my mysql arrays are objects.

So you can do something like:

connection.query('SELECT * FROM Company', function(err, rows, fields) {
if (err) throw err;

  for (var i = 0; i < rows.length; i++) {
    for (obj of rows[i]) {
       //obj = whatever field its currently on (name, email, w/e)
       theShit = "";
       theShit += ('| ' + rows[i].name + ' | ' + rows[i].address_zip);
       theEmail += theShit + "<BR>";
  }
}
like image 114
Datsik Avatar answered Dec 21 '22 09:12

Datsik


I was able to solve the same by the following code.

Object.keys(result.rows[index]).forEach(function(key) {
  var val = result.rows[index][key];
  console.log('key is: ' + key);
  console.log('val is: ' + val);
});
like image 35
Mohd Arshil Avatar answered Dec 21 '22 07:12

Mohd Arshil