我有一个返回类似于以下内容的查询:
[ RowDataPacket { username: 'mario', content: 'foo', quantity: 4 },
RowDataPacket { username: 'mario', content: 'bar', quantity: 6 },
RowDataPacket { username: 'mario', content: 'fizz', quantity: 4 } ]
我想合并所有的RowDataPacket并返回
{
mario: {
foo: 4,
bar: 4,
fizz: 4
}
}
如何转换记录?
最佳答案
Array.prototype.reduce()是你的 friend 。
像这样的东西应该可以解决问题:
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] || { }) }), { });
对于单行来说有点神秘,所以你可能想要扩展它。
关于mysql - 将 RowDataPacket 记录合并为一个并返回 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48637545/