我的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
获得输出?
答案 0 :(得分:2)
直接的实施是
_.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')
等一样使用此迭代。您甚至可以通过以下方式推广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')
答案 1 :(得分:0)
var _ = require('lodash'); //lodash 4.5
var hotels = [
{"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"}}
]
var filteredItems = _.filter(hotels, function(hotel){
return _.inRange(hotel.hoteldetail.mitrate, 500, 7500);
});