I need to transfrm an array into another array but can't find a good way to do this. An error message tells me I can't push into found[0].children, but I feel like all the way I'm doing it wrong and dirty; would you tell me how you manage this kind of issue?
I would like to transform the array:
const input =
[
{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 array:
const output =
[
{
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'
}
]
}
];
Here is what I tried, but I am not satisfied at all with this idea, which doesn't seem like the good way...
function dateoptions(dateslist) {
var options: any[] = [];
dateslist.forEach(element => {
var tab = element.value.split(' ');
var dt = tab[0];
var time = tab[1];
var found = options.filter(opt=> opt.id==dt);
if (found.length>0) {
// I can't do this:
found[0].children.push({
'id': time,
'label': time,
disabled: element.visible==0
});
}
else {
options.push({
'id': dt,
'label': dt,
'children': {'id':time, 'label': time, disabled: element.visible==0}
});
}
});
return options;
}
optionsstructure to be sure please ? note : you are using forEach method but you keep returns options. it does nothing