I'm struggling to transform an array into another array and keep running into errors. Specifically, I can't figure out how to push into found[0].children
. It feels like my current approach is messy and incorrect. Can someone provide guidance on how to tackle this issue more effectively?
My goal is to convert the following input array:
const data =
[
{value: "29-08-2020 16:00", visible: 0},
{value: "29-08-2020 16:30", visible: 1},
{value: "29-08-2020 17:00", visible: 0},
{value: "30-08-2020 15:00", visible: 1},
{value: "30-08-2020 15:30", visible: 1}
];
Into the desired output array structure:
const result =
[
{
id: '29/08/2020',
label: '29/08/2020',
children:
[
{
id: '16:00',
label: '16:00',
isDisabled: true
},
{
id: '16:30',
label: '16:30'
},
{
id: '17:00',
label: '17:00',
isDisabled: true
}
],
},
{
id: '30/08/2020',
label: '30/08/2020',
children:
[
{
id: '15:00',
label: '15:00'
},
{
id: '15:30',
label: '15:30'
}
]
}
];
I've attempted a solution using the following function, but I'm not satisfied with it as it doesn't feel like the best way to approach the problem:
function convertDates(inputData) {
var outputData = [];
inputData.forEach(element => {
var splitValues = element.value.split(' ');
var date = splitValues[0];
var time = splitValues[1];
var foundEntry = outputData.filter(entry => entry.id == date);
if (foundEntry.length > 0) {
foundEntry[0].children.push({
'id': time,
'label': time,
disabled: element.visible == 0
});
} else {
outputData.push({
'id': date,
'label': date,
'children': {'id': time, 'label': time, disabled: element.visible == 0}
});
}
});
return outputData;
}