Reputation: 117
I am trying to get a list of distinct values from a MySQL Column and return these in a single JSON array.
I have this current code:
app.get('/experiences/', function(req, res) {
res.setHeader('Access-Control-Allow-Origin', http://localhost:3000');
connection.query('SELECT DISTINCT experience FROM questions', function(err, data) {
err ? res.send(err) : res.json(data);
});
});
I want the result to look like:
{experience: ["1-3","1-5","5+"]}
but it currently looks like:
[{"experience":"1-3"},{"experience":"1-5"},{"experience":"5+"}]
Upvotes: 0
Views: 432
Reputation: 536
You can reformat the data object you get by looping on the array and recreate an object with the correct format.
Like this :
connection.query('SELECT DISTINCT experience FROM questions', function(err, data) {
if(err)
res.send(err)
else {
let experiences = [];
data.forEach(function(
experiences.push(d.experience);
}
result = {experience : experiences };
res.json(result);
}
});
Upvotes: 1