0

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+"}]
0

1 Answer 1

1

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);
    }
});
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.