Push partial result data in array and send

家住魔仙堡 提交于 2019-12-23 02:34:48

问题


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

});

回答1:


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



回答2:


This is not MySQL way to achieve what you wanted. I have a JS way to achieve what you need.

    var a = [{"id":1,"tags":"tag1, tag2, tag3"},{"id":2,"tags":"tag2, tag4"}];
    var expected =[];
    a.forEach( function (eachObj){
        var obj = {};
        for (var key in eachObj) {
            if (eachObj.hasOwnProperty(key) && key ==='tags'){
                obj[key] = [eachObj[key]];
            }else{
                obj[key] = eachObj[key];
            }
        }
        expected.push(obj);
    });

    console.log(expected);


来源:https://stackoverflow.com/questions/46391749/push-partial-result-data-in-array-and-send

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!