[英]Merge RowDataPacket records in one and return JSON
我有一個查詢,返回的內容類似於:
[ 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()是您的朋友。
這樣的事情應該可以解決問題:
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] || { }) }), { });
一個內襯有點神秘,所以您可能需要擴展它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.