0

I need to change format of my data which I obtained from db. Data have this format:

[
    {
        "id": 2,
        "report_id": null,
        "parking_lot_id": null,
        "message": "test2",
        "date": "2022-03-11",
        "seen": false,
        "category": "report",
        "user_id": 3
    },
    {
        "id": 3,
        "report_id": null,
        "parking_lot_id": null,
        "message": "test3",
        "date": "2022-03-11",
        "seen": false,
        "category": "report",
        "user_id": 3
    },
    {
        "id": 1,
        "report_id": null,
        "parking_lot_id": null,
        "message": "test",
        "date": "2022-03-03",
        "seen": true,
        "category": "report",
        "user_id": 3
    },
...
]

Format which I need to get. (Grouped all notifications bysame date)

[
  {
    date: new Date(),
    notifications: [
      {
        id: 0,
        message: 'Foo',
        date: new Date(),
        category: 'Web app',
        seen: true
      },
      {
        id: 1,
        message: 'Test',
        date: new Date(),
        category: 'Web app',
        seen: false
      }
    ]
  },
...

Is there any easy way to do this? It will be best to obtain data in this format from database but I think that is not possible...

The way I am getting the data from db looks like this (I am using knex framework) :

export async function getAllUserNotifications(request) {
  const userNotifications: any[] = await getUserNotifications(request.params.userId, queryBuilder(request));
  return userNotifications.length > 0 ? userNotifications : []
}

export async function getUserNotifications(userId: string, knex: Knex<any, unknown[]>,limit?:number) {
  return await knex('notification')
    .select('*')
    .where({ 'user_id': userId })
    .limit(limit ? limit : 10)
    .orderBy('date', 'desc')
}
Young L.
  • 922
  • 3
  • 13
  • 33
  • Why does `'2022-03-03'` become `new Date()`? – evolutionxbox Mar 11 '22 at 12:54
  • or [How can I group an array of objects by key?](https://stackoverflow.com/questions/40774697/how-can-i-group-an-array-of-objects-by-key) or [Most efficient method to groupby on an array of objects](https://stackoverflow.com/questions/14446511/most-efficient-method-to-groupby-on-an-array-of-objects) – pilchard Mar 11 '22 at 12:56
  • That´s just copy of my interface I am using in my front-end. There is important only that object containing date and notifications part. – Young L. Mar 11 '22 at 12:56

0 Answers0