2

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

2
  • ["2020-01-01":{"COL1": "VALUE_COL_1", "COL2": "VALUE_COL_2"}] is not valid. Do you mean {{"2020-01-01":{"COL1": "VALUE_COL_1", "COL2": "VALUE_COL_2"}} ? Commented Apr 2, 2020 at 14:20
  • Yes, sorry for the typo. I edited. Commented Apr 2, 2020 at 14:22

1 Answer 1

1

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.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.