我的json数组看起来像这样

        [
        {"hoteldetail":{"hotelid":"00007111","hotelname":"hjghghg","minrate":"500"},
        {"hoteldetail"{"hotelid":"00007111","hotelname":"hjghghg","minrate":"1200"},
        {"hoteldetail":{"hotelid":"00007111","hotelname":"hjghghg","minrate":"7000"},
        {"hoteldetail":{"hotelid":"00007111","hotelname":"hjghghg","minrate":"8000"}

        ]


从这个我想获取minrate范围内的项目

例如:如果minrate范围是(500,7500),它将从json数组中返回仅包含上述范围内的minrate的项。

那么如何使用lodash获得输出?

最佳答案

简单的实现是

_.filter(arr, item => _.inRange(item.hoteldetail.minrate, 500, 7501))


它的工作原理与所读取的完全一样:为属性hoteldetail.minrate在指定范围内的项过滤数组。但是,较新的lodash具有一个非常好的功能,称为_.iteratee,它使您可以提供过滤器的简写形式,例如:

_.filter(arr, 'minrate in range 500, 7500')


这是实现

_.iteratee = _.wrap(_.iteratee, function(callback, func) {
  var p = /minrate in range (\d+), (\d+)/g.exec(func);
  return !p ? callback(func) : function(object) {
    return object.hoteldetail.minrate >= p[1] && object.hoteldetail.minrate <= p[2];
  };
});


您可以像编写英语_.filter(arr, 'minrate in range 100, 200')_.filter(arr, 'minrate in range 5000, 6000')等一样使用此iteratee。甚至可以按以下方式推广minrate

_.iteratee = _.wrap(_.iteratee, function(callback, func) {
  var p = /(minrate|number\ of\ rooms) in range (\d+), (\d+)/g.exec(func);
  return !p ? callback(func) : function(object) {
    var prop = object.hoteldetail[p[1]];
    return prop >= p[2] && prop <= p[3];
  };
});


并将其用作_.filter(arr, 'number of rooms in range 1, 5')

Doc:https://lodash.com/docs#iteratee

08-19 06:47