I have a array of object like this :
{
"data": [
{
"id": 1,
"from": "2022-08-01",
"to": "2022-08-05",
"description": "test 1",
"files": [
{
"id": 1,
"hospital_name": "hospital 11",
"hospital_id": 11,
"period_id": 1
},
{
"id": 2,
"hospital_name": "hospital 11",
"hospital_id": 11,
"period_id": 1
}
]
},
{
"id": 2,
"from": "2022-08-06",
"to": "2022-08-10",
"description": "test 2",
"files": [
{
"id": 3,
"hospital_name": "hospital 12",
"hospital_id": 12,
"period_id": 2
},
{
"id": 4,
"hospital_name": "hospital 12",
"hospital_id": 12,
"period_id": 2
}
]
}
]
}
I want to convert the array to be like this :
{
"data": [
{
"id": 1, // this is period id
"hospital_name": "hospital 11",
"hospital_id": 11,
"from": "2022-08-01",
"to": "2022-08-05",
"description": "test 1"
},
{
"id": 2,
"hospital_name": "hospital 12",
"hospital_id": 12,
"from": "2022-08-06",
"to": "2022-08-10",
"description": "test 2"
}
]
}
So I expect the results like that
I try to type my code like this :
data.flatMap((period) =>
period.files.map((file) => ({
id: period.id,
hospital_name: file.hospital_name,
hospital_id: file.hospital_id,
from: period.from,
to: period.to,
description: period.description,
}))
)
But the problem is my code show duplicate id
How can I solve my problem?
Note :
Every period only has one hospital id