[英]Merge RowDataPacket records in one and return JSON
I've a query that returns a content similar to: 我有一个查询,返回的内容类似于:
[ RowDataPacket { username: 'mario', content: 'foo', quantity: 4 },
RowDataPacket { username: 'mario', content: 'bar', quantity: 6 },
RowDataPacket { username: 'mario', content: 'fizz', quantity: 4 } ]
I want to merge all the RowDataPacket and return 我想合并所有RowDataPacket并返回
{
mario: {
foo: 4,
bar: 4,
fizz: 4
}
}
How can I convert records? 如何转换记录?
Array.prototype.reduce() is your friend here. Array.prototype.reduce()是您的朋友。
Something like this should do the trick: 这样的事情应该可以解决问题:
const rows = [
{ username: 'mario', content: 'foo', quantity: 4 },
{ username: 'mario', content: 'bar', quantity: 6 },
{ username: 'mario', content: 'fizz', quantity: 4 }
];
const response = rows.reduce((acc, row) => Object.assign(acc, { [row.username]: Object.assign({ [row.content]: row.quantity }, acc[row.username] || { }) }), { });
A bit cryptic for a one liner, so you may want to expand that. 一个内衬有点神秘,所以您可能需要扩展它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.