Search code examples
javascriptunderscore.jslodash

How to omit values while using groupby


I have an array of JSON objects like the following:

{ BlockId: '979',
Day: 'Preliminary/Final Qualifying  Day 1',
Event: 'Preliminary Qualifying',
FirstName: 'some',
LastName: 'one',
PlayerPosition: '6',
TimeSlot: '4/21/2018 12:00:00 PM' 
}

I wanted to group the objects based on values and did the following:

var result = _(json)
.groupBy('Day')
.mapValues(function(groupedByDay) {
    return _(groupedByDay)
    .groupBy('Event')
    .mapValues(function (groupedByDayAndEvent) {
        return _.groupBy(groupedByDayAndEvent, 'BlockId');
    })
    .value();
})
.value();

Which gave me the following:

{"Preliminary/Final Qualifying  Day 1":
    {"Preliminary Qualifying":
        { "977":[{"BlockId":"977",
                  "Day":"Preliminary/Final Qualifying  Day 1", 
                  "Event":"Preliminary Qualifying",
                  "FirstName":"some",
                  "LastName":"one",
                  "PlayerPosition":"0",
                  "TimeSlot":"4/21/2018 9:00:00 AM"
                 }]
         }
     }
 }

I'd like to remove the fields that I grouped by. Namely: BlockId, Day and Event. Any ideas on how I could omit these values with the code I presented? I'm lost :(

EDIT:

It seems that I forgot that _.omit creates a copy of the object without the fields given... I came to this solution that I don't believe is efficient at all. Any suggestions to make it better?

for(var day in result) {
    for(var event in result[day]) {
        for(var block in result[day][event]) {
            for(var item in result[day][event][block]) {
                delete result[day][event][block][item].BlockId;
                delete result[day][event][block][item].Day;
                delete result[day][event][block][item].Event;
            }
        }
    }
}

Solution

  • use _omit in the deepest level

    let myArr = [{
      "BlockId": "979",
      "Day": "Preliminary/Final Qualifying  Day 1",
      "Event": "Preliminary Qualifying",
      "FirstName": "Robert",
      "LastName": "Oristaglio",
      "PlayerPosition": "6",
      "TimeSlot": "4/21/2018 12:00:00 PM"
    }]
    
    var result = _(myArr)
      .groupBy('Day')
      .mapValues(function(groupedByDay) {
        return _(groupedByDay)
          .groupBy('Event')
          .mapValues(function(groupedByDayAndEvent) {
            return _(groupedByDayAndEvent)
              .groupBy('BlockId')
              .mapValues(function(groupedByAll) {
                return groupedByAll.map(function(entry) {
                  return _.omit(entry, ['Day', 'Event', 'BlockId']);
                })
              })
              .value();
          })
          .value();
      })
      .value();
    
    console.log(result)
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js"></script>