Please reorganize code below, for example you could create one function for grouping, with result like this:
{weekday: {'starts': [], 'ends': []}}

After that you should be able to create final structure for api with one loop here.