Search code examples
mysqlnode-mysql

Push partial result data in array and send


I have a MySQL table in which a column name is tags and type is VARCHAR. I'm inserting the data with comma separated:

tag1, tag2, tag3, tag4, tag5, tag6

My query from node is:

app.get('/tagtest', (req, res) => {

    var tags = [];       // <= Not sure if I need this or how to push tags here.

    connection.query("SELECT * FROM tagtestpost", (err, rows)=>{
        res.send(rows)
    });

}); 

Response from above query is:

[{"id":1,"tags":"tag1, tag2, tag3"},{"id":2,"tags":"tag2, tag4"}]

I want to return the tags in an array. So the response should look like:

[{"id":1,"tags":[tag1, tag2, tag3]},{"id":2,"tags":[tag2, tag4]}]

How can I achieve this?

UPDATE1

app.get('/showtagposts', (req, res) => {

    connection.query("SELECT * FROM postwithtagtest", (err, rows)=>{

        var a = rows;

    const expected = a.map((post) => ({
        ...post,
        tags: post.tags.split(/,\s+/)
    }));

    console.log(expected);

            res.json(expected);
    });

});

Solution

  • The accepted answer doesn't actually split the tags into separate values within an array. The following does:

        const a = [{"id":1,"tags":"tag1, tag2, tag3"},{"id":2,"tags":"tag2, tag4"}];
    
        // ES6
        const expected = a.map((post) => ({
            ...post,
            tags: post.tags.split(/,\s+/)
        }));
    
        // ES5
        const expected = a.map(function (post) {
            return Object.assign({}, post, {
                tags: post.tags.split(/,\s+/)
            });
        });
    
        console.log(expected);

    Update

    It appears that the spread operator does not work with object when using Node. See here: Node v6 failing on object spread

    I've changed it to use Object.assign instead.

    app.get('/showtagposts', (req, res) => {
        connection.query("SELECT * FROM postwithtagtest", (err, rows) => {
            const data = rows.map((post) => {
                return Object.assign({}, post, {
                    tags: post.tags.split(/,\s+/)
                });
            });
    
            res.json(data);
        });
    });