Considering this simplified formData:
FormData {
"id": "id1",
"timeslots[0][start]": "2023-06-10",
"timeslots[0][end]": "2023-06-09",
"timeslots[1][start]": "2024-06-10",
"timeslots[1][end]": "2024-06-09",
....
}
or parsed object (I have access to both):
{
id: "id1",
"timeslots[0][start]": "2023-06-10",
"timeslots[0][end]": "2023-06-09",
"timeslots[1][start]": "2024-06-10",
"timeslots[1][end]": "2024-06-09",
...
}
What would be the simplest but readable way to transform timeslots into an array?
In fine, I'd like to get this object:
{
id: "id1",
timeslots:[
{ start: "2023-06-10", end: "2023-06-09" },
{ start: "2024-06-10", end: "2024-06-09" }
]
}
I've begun with this (in JS). But I don't think it driving me somewhere...
const timeslots = []
for (const [key, value] of Object.entries(body)) {
if (key.startsWith('timeslots')) {
const new_key = key.substring(13, key.length - 1)
const slot = key.substring(10, 11)
const tmp = { [new_key]: value, number: slot }
timeslots.push(tmp)
...
}
}
===== EDIT ======
Considering this augmented object:
{
id: "id1",
"timeslots[0][start]": "2023-06-10",
"timeslots[0][end]": "2023-06-09",
"timeslots[0]disability[3]": "D3",
"timeslots[0]disability[4]": "D4"
"timeslots[1][start]": "2024-06-10",
"timeslots[1][end]": "2024-06-09",
"timeslots[1]disability[1]": "D1",
"timeslots[1]disability[5]": "D5"
...
}
How to update @newalvaro9 answer to get this object?
{
id: "id1",
timeslots:[
{ start: "2023-06-10", end: "2023-06-09", disability: ['D3', 'D4'] },
{ start: "2024-06-10", end: "2024-06-09", disability: ['D1', 'D5'] }
]
}