gpt4 book ai didi

underscore.js - 如何在 underscore.js 中处理 JSON 日期

转载 作者:行者123 更新时间:2023-12-03 16:20:41 27 4
gpt4 key购买 nike

如何在 underscore.js 中查询日期?我知道我不能做“之间”子句,但请参阅下面的代码作为示例。我的目标是根据用户指定的日期范围将 JSON 数据加载到图表中。

var testdata=[{"date": "1/8/2014", "y": 50, "z": 466, "a": 35},
{"date": "1/9/2014", "y": 325, "z": 201, "a": 85},
{"date": "1/10/2014", "y": 250, "z": null, "a": 40},
{"date": "1/11/2014", "y": 125, "z": 500, "a": 60},
{"date": "1/12/2014", "y": 50, "z": 466, "a": 35},
{"date": "1/13/2014", "y": 325, "z": 201, "a": 85}
];

daterange = _.select(testdata, function(getdates){ return getdates between '1/9/2014' and '1/12/2014';});
console.log(daterange);

更新:我在获取日期回调以替换 Gruff Bunny 示例中的“startDate”和“endDate”时遇到了一些麻烦。有什么建议?
var cb = function(start, end) {
$('#reportrange span').html(start.format('MMMM D, YYYY') + ' - ' + end.format('MMMM D, YYYY'));
alert("Callback has fired: [" + start.format('MMMM D, YYYY') + " to " + end.format('MMMM D, YYYY') + "]");

var testdata=[
{"date": "1/2/2014", "y": 250, "z": null, "a": 40},
{"date": "1/3/2014", "y": 125, "z": 500, "a": 60},
{"date": "1/4/2014", "y": 50, "z": 466, "a": 35},
{"date": "1/5/2014", "y": 325, "z": 201, "a": 85},
{"date": "1/6/2014", "y": 250, "z": null, "a": 40},
{"date": "1/7/2014", "y": 125, "z": 500, "a": 60},
{"date": "1/8/2014", "y": 50, "z": 466, "a": 35},
{"date": "1/9/2014", "y": 325, "z": 201, "a": 85},
{"date": "1/10/2014", "y": 250, "z": null, "a": 40},
{"date": "1/11/2014", "y": 125, "z": 500, "a": 60},
{"date": "1/12/2014", "y": 50, "z": 466, "a": 35}
];

_.each(testdata, function(data){
var dateParts = data.date.split('/')
data.date = new Date(dateParts[2], dateParts[0] - 1, dateParts[1])
});

var startDate = new Date(2014,0,9) ;
var endDate = new Date(2014,0,12) ;

var requiredData = _.filter(testdata, function(data){
return data.date >= startDate && data.date <= endDate;
});

最佳答案

这些日期不容易处理,因此首先将它们全部转换为 javascript 日期:

_.each(testdata, function(data){
var dateParts = data.date.split('/')
data.date = new Date(dateParts[2], dateParts[0] - 1, dateParts[1])
});

然后使用 _.filter 提取你想要的数据:
var startDate = new Date(2014,0,9) ;
var endDate = new Date(2014,0,12) ;

var requiredData = _.filter(testdata, function(data){
return data.date >= startDate && data.date <= endDate;
});

关于underscore.js - 如何在 underscore.js 中处理 JSON 日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21614614/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com