Reputation: 453
I use this very beginner's skill code to get some info from a mysql database:
var sql_select = "SELECT COL1, COL2 FROM MYTABLE WHERE ID = ? LIMIT 1"
connection.query(sql_select, Id, (error, results) => {
if (error){
return console.error(error.message);
}
console.log("result:", results);
});
I know how to get results from SQL select into JSON and get something like :
[{"COL1": "VALUE_COL_1", "COL2": "VALUE_COL_2"}]
but how can i get something like this instead?
[{"2020-01-01":{"COL1": "VALUE_COL_1", "COL2": "VALUE_COL_2"}]
(2020-01-01 would be a variable date set upper in the code).
Thanks
Upvotes: 2
Views: 58
Reputation: 108651
This is a job for forEach
, push
, and using the bracket form of the property accessor to set an property in an object.
const output = [] // empty new array
results.forEach ( row => {
const x = {} // empty object
x[theDateStringFromSomeplaceElse] = row // your row as value, date as name
output.push( x ) // push into the output array
} )
// now output has the array you want.
Upvotes: 1