-2

I'm pulling multiple rows from a node.js MySQL query, and I would like the format to be:

["value1","value2","value3"]

however my current result is:

[{"temperature":value1},{"temperature":value2},{"temperature":value3}]

I don't want the key, it's all data from the same MySQL column.

var sql = "SELECT temperature FROM temperatures";
        con.query(sql, function (err, result) {
            if (err) throw err;
                console.log(result);
                let data = JSON.stringify(result);
                fs.writeFileSync('results.json', data);

I got time to rewrite the code. Thanks all, the map function worked excellently.

var sql = "SELECT temperature FROM temperatures";
        con.query(sql, function (err, result) {
            if (err) throw err;
                var newresult = result.map( value => value.temperature);
                let data = JSON.stringify(newresult);
                console.log('Queried JSON Data: \n' + data + '\n');
                fs.writeFileSync('results.json', data);
        });
    };
Neal
  • 9
  • 4

2 Answers2

0

you can use forEach or Map

var kvArray = [{"temperature":"value1"},{"temperature":"value1"},{"temperature":"value1"}];

//example for map.
var rObj = kvArray.map( value => value.temperature);

//example for foreach.

var rObj = [];
kvArray.forEach( (value) => { 
   return rObj.push(value.temperature);   
});

console.log(kvArray , rObj)
// rObj = (3) ["value1", "value1", "value1"]

// kvArray is still: 
//[{"temperature":"value1"},{"temperature":"value1"},{"temperature":"value1"}];

Julius Limson
  • 526
  • 9
  • 29
0

I'm scanning the array of dictionaries and each time joining the values of each dictionary. This is more general approach, meaning even if you have multiple values in each dictionary it will work the same.

let make_results = (result) => {
  let values_only = [];
  result.forEach((r) => {
    values_only = values_only.concat(Object.values(r));
  });
  return values_only;
}

let result = [{
  "temperature": 1
}, {
  "temperature": 2
}, {
  "temperature": 3
}];

console.log(make_results(result));

Then I'm just using make_results function in your code:

var sql = "SELECT temperature FROM temperatures";
        con.query(sql, function (err, result) {
            if (err) throw err;
                console.log(result);
                let data = JSON.stringify(make_results);
                fs.writeFileSync('results.json', data);
Omri Attiya
  • 3,917
  • 3
  • 19
  • 35