Lodash过滤独特的文件

时间:2017-01-02 14:40:06

标签: filter lodash

如何过滤当前数据:

[{
    key: 'T1',
    legs:[{ fno: 'W321',date: '2017-01-02 18:20:00.000+0200'}],
    fare: { type: 'B', price: 25 }
},{
    key: 'T1',
    legs:[{ fno: 'W321', date: '2017-01-02T18:20:00.000+0200'}],
    fare: { type: 'E', price: 23 }
},{
    key: 'T1',
    legs:[{ fno: 'W321', date: '2017-01-02T18:20:00.000+0200'}],
    fare: { type: 'E', price: 20}
}]

我希望按legs[0].fnolegs[0].datefare.type进行分组,并保留每组中价格最低的商品。这是预期的结果:

[{
    key: 'T1',
    legs:[{ fno: 'W321',date: '2017-01-02T18:20:00.000+0200'}],
    fare: { type: 'B', price: 25}
},{
    key: 'T1',
    legs:[{ fno: 'W321',date: '2017-01-02T18:20:00.000+0200'}],
    fare: { type: 'E',  price: 20}
}]

1 个答案:

答案 0 :(得分:0)

_.groupBy()与回调一起使用以创建要分组的字符串,然后使用_.minBy() _.map()将每个组分配到单个项目:

var data = [{"key":"T1","legs":[{"fno":"W321","date":"2017-01-02 18:20:00.000+0200"}],"fare":{"type":"B","price":25}},{"key":"T1","legs":[{"fno":"W321","date":"2017-01-02T18:20:00.000+0200"}],"fare":{"type":"E","price":23}},{"key":"T1","legs":[{"fno":"W321","date":"2017-01-02T18:20:00.000+0200"}],"fare":{"type":"E","price":20}}];

var result = _(data)
  // group by the combined group keys
  .groupBy(function(o) {
    // extract all group keys and join them to a string
    return _.at(o, ['key', 'legs[0].date', 'fare.type']).join('');
  })
  .map(function(group) {
     // get the object object with the minimum fare.price
     return _.minBy(group, 'fare.price');
   })
  .value();

console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>