如何在使用groupby时省略值

时间:2018-04-09 00:05:41

标签: javascript underscore.js lodash

我有一个JSON对象数组,如下所示:

{ 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' 
}

我想根据值对对象进行分组,并执行以下操作:

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

这给了我以下内容:

{"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"
                 }]
         }
     }
 }

我想删除我分组的字段。即:BlockId, Day and Event.有关如何使用我提供的代码省略这些值的任何想法?我输了:(

编辑:

似乎我忘了_.omit创建了一个没有给出字段的对象的副本......我来到这个我不相信有效的解决方案。有什么建议让它更好吗?

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;
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

在最深层次使用_omit

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>