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')
}