【问题标题】:Merge RowDataPacket records in one and return JSON合并 RowDataPacket 记录并返回 JSON
【发布时间】:2018-07-16 04:38:07
【问题描述】:

我的查询返回的内容类似于:

[ 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
    }
}

如何转换记录?

【问题讨论】:

    标签: mysql json node.js


    【解决方案1】:

    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] || { }) }), { });
    

    对于单行来说有点神秘,所以你可能想要扩展它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-15
      相关资源
      最近更新 更多