我想按属性值过滤JavaScript对象。这是一个场景:
以下数组是我正在使用
的一个小例子 var array = [{
"Title": "July 13 - July 19 2014",
"displayAd_imp": "15,242,505",
"Date": "2014-07-17T00:00:00.000Z",
"WeekNo": 29
}, {
"Title": "July 20 - July 26 2014",
"displayAd_imp": "15,942,705",
"Date": "2014-07-24T00:00:00.000Z",
"WeekNo": 30
}, {
"Title": "July 27 - Aug 2 2014",
"displayAd_imp": "15,683,545",
"Date": "2014-07-31T00:00:00.000Z",
"WeekNo": 31
}, {
"Title": "Aug 3 - Aug 9 2014",
"displayAd_imp": "15,042,005",
"Date": "2014-08-07T00:00:00.000Z",
"WeekNo": 32
}, {
"Title": "Aug 10 - Aug 17 2014",
"displayAd_imp": "15,442,605",
"Date": "2014-08-14T00:00:00.000Z",
"WeekNo": 33
}]
在我的应用中,有两个下拉字段可供用户选择一系列周。我正在通过“日期”计算周数并插入“WeekNo”作为属性。我想使用WeekNo来获取基于起始端值的一大块数据。
示例是如果开始日期是第29周并且结束是第32周,则该方法将返回相关数据。
如果有人想要更新它,我会Jsfiddle。
提前感谢!
答案 0 :(得分:3)
您可以使用Array.filter功能。您可以直接在阵列上调用它,然后提供回调。如果该回调返回true,则该元素将包含在从filter
返回的新数组中。
例如:
var newArr = array.filter(function(item) {
return (item.WeekNo >= 29 && item.WeekNo < 32);
});
答案 1 :(得分:0)
var array = [{
"Title": "July 13 - July 19 2014",
"displayAd_imp": "15,242,505",
"Date": "2014-07-17T00:00:00.000Z",
"WeekNo": 29
}, {
"Title": "July 20 - July 26 2014",
"displayAd_imp": "15,942,705",
"Date": "2014-07-24T00:00:00.000Z",
"WeekNo": 30
}, {
"Title": "July 27 - Aug 2 2014",
"displayAd_imp": "15,683,545",
"Date": "2014-07-31T00:00:00.000Z",
"WeekNo": 31
}, {
"Title": "Aug 3 - Aug 9 2014",
"displayAd_imp": "15,042,005",
"Date": "2014-08-07T00:00:00.000Z",
"WeekNo": 32
}, {
"Title": "Aug 10 - Aug 17 2014",
"displayAd_imp": "15,442,605",
"Date": "2014-08-14T00:00:00.000Z",
"WeekNo": 33
}]
var predicate = function(start, end) {
return function(array) {
return _.inRange(array.WeekNo, start, end + 1);
}
}
var result = _.filter(array, predicate(29, 32));
console.log('inRange', result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.16.4/lodash.min.js"></script>