简体   繁体   中英

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

{
    mario: {
        foo: 4,
        bar: 4,
        fizz: 4
    }
}

How can I convert records?

Array.prototype.reduce() is your friend here.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM