将部分结果数据推入数组并发送 [英] Push partial result data in array and send
问题描述
我有一个 MySQL 表,其中的列名为 tags
,类型为 VARCHAR
.我用逗号分隔插入数据:
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
我来自节点的查询是:
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)
});
});
上述查询的响应是:
[{"id":1,"tags":"tag1, tag2, tag3"},{"id":2,"tags":"tag2, tag4"}]
我想返回数组中的标签.所以 response
应该是这样的:
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?
更新1
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);
});
});
推荐答案
接受的答案实际上并未将标签拆分为数组中的单独值.执行以下操作:
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);
更新
使用 Node.js 时,似乎扩展运算符不适用于对象.请参阅此处:Node v6 对象传播失败
It appears that the spread operator does not work with object when using Node. See here: Node v6 failing on object spread
我已将其更改为使用 Object.assign
.
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);
});
});
这篇关于将部分结果数据推入数组并发送的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!