Shavin Peiris Shavin Peiris - 5 months ago 8
AngularJS Question

How do I filter and structure this JSON?

I have a array of json objects known as events, which has fields like eventId, eventName and most importantly dateofevent.

[{event1}, {event2}, {event3}];

I need to iterate over this array of events and filter out the events that are on the same day. To obtain a new object like this.

"days": [
{
"date": "11-05-2015",
"events": [
{"eventId": 1, ...},
{"eventId": 2, ...},
{"eventId": 3, ...},
{"eventId": 4, ...},
]
},


How can I do this efficiently with Javascript or Angular?

Answer

You can create a new object with the dates as keys, and the values are arrays that contain the events. After you have the date => events map, convert it to array in the structure you want.

Assuming the original data is in a variable called "events":

    var events  = [{event 1}, {event 2}...];
    var daysMap = {};
    var days = [];
    events.map(function(event) {
        if (days[event.dateofevent] === undefined) {
            days[event.dateofevent] = [];
        }
        days[event.dateofevent].push(event);
    });
    for (var day in daysMap) {
        days.push({
            date: day, 
            events: daysMap[day]
        });
    }
Comments