【问题标题】:Filter JSON by range dates JS按范围日期过滤 JSON JS
【发布时间】:2018-06-19 18:05:16
【问题描述】:

我想按日期范围过滤一个简单的 JSON 文件。 带有开始日期和结束日期。

这是我的功能:

var startDate = new Date("2013-3-25");
var endDate = new Date("2017-3-25");
var aDate = new Date();

var filteredData = this.orders.filter(function(a){
aDate = new Date(a.fecha);
    aDate >= startDate && aDate <= endDate;
});
console.log(filteredData)

这是我的:fiddle

我希望在我的数组中获得一个对象,但是正如您在控制台中看到的那样,该数组是空的。

【问题讨论】:

    标签: javascript json date filtering


    【解决方案1】:

    当您对数组使用filter 方法时,该函数需要返回一个布尔值来指示脚本是保留一个值还是删除它。

    您没有从过滤器函数中返回值。这有效:

    var filteredData = this.orders.filter(function(a){
        aDate = new Date(a.fecha);
        return aDate >= startDate && aDate <= endDate;
    });
    

    【讨论】:

    • 不敢相信我错过了。谢谢!
    • @xxxxxxxxxxxxx 不要忘记“接受”答案! :)
    【解决方案2】:

    但是数组是空的,你可以在控制台中使用。

    因为filter的回调方法是不返回任何东西,就让它

    var filteredData = this.orders.filter(function(a){
        var aDate = new Date(a.fecha);
        return aDate.getTime() >= startDate.getTime() && aDate.getTime() <= endDate.getTime();
    });
    

    注意

    • 日期比较的方式不同,请查看this answer
    • 你不需要为每次迭代在startDateendDate 上执行getTime(),在filter 之前执行一次

    【讨论】:

    • 感谢您的回答和时间!你是对的回报。但是,比较日期会以动态方式出现,这只是我快速完成的。
    • @xxxxxxxxxxxxx 当然,我添加了详细信息只是为了完成答案。希望这会有所帮助!
    【解决方案3】:

    您没有在过滤器中返回任何内容。

    var filteredData = this.orders.filter(function(a){
        aDate = new Date(a.fecha);
        return aDate >= startDate && aDate <= endDate;
    });
    

    供参考,https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-09
      相关资源
      最近更新 更多