I am trying to get data from mysql with javascript and then do some things with each of the results. I have saved the mysql result to a variable and thought that I could iterate through this, but I cant understand how to do it.
To make it easy I have simplified the code as below, which uses forEach():
connection.query("SELECT length, weight FROM physics WHERE user = 'Test' AND name = 'Hi'", function (err, result) {
if (err) throw err;
allres = result;
allres.forEach(function(name) {
console.log(`I looped: ${name}`);
});
});
The result is:
I looped: [object Object]
I looped: [object Object]
I looped: [object Object]
If I do console.log(allres) I get:
RowDataPacket { length: '5', weight: '3' },
RowDataPacket { length: '11', weight: '11' },
RowDataPacket { length: '2', weight: '2' },
So the values are there, but how can I loop this?
I looped: ${name},toString()get's called onname, which for objects returns[object Object]. Instead, try accessing properties on the object, likeI looped: ${name.length}, or convert the object to JSON:I looped: ${JSON.stringify(name)}