如何按时间对JSON数组排序?(不像以前建议的那样工作) [英] How to sort JSON array with time??( not working as suggested before)

查看:547
本文介绍了如何按时间对JSON数组排序?(不像以前建议的那样工作)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

参考此问题排序json数组

我使用ajax使用以下JSON字符串,并将对象存储为数组:

I have the following JSON String using ajax and store the object as an array:

var homes = [
    {
     "h_id":"3",
     "city":"Dallas",
     "state":"TX",
     "zip":"75201",
     "price":"162500",
     "start_time":"2011-01-26 08:00:00",
     "end_time":"2011-01-26 05:00:00"
    },
    {
     "h_id":"4",
     "city":"Bevery Hills",
     "state":"CA",
     "zip":"90210",
     "price":"319250",
     "start_time":"2011-01-26 12:00:00",
     "end_time":"2011-01-26 05:00:00"
    },
    {
     "h_id":"5",
     "city":"New York",
     "state":"NY",
     "zip":"00010",
     "price":"962500",
     "start_time":"2011-01-28 08:00:00",
     "end_time":"2011-01-26 05:00:00"
    }
    ];

如何创建一个函数来对ASC中的"start_date"字段进行排序,并仅使用JavaScript按DESC顺序进行排序?

How do I create a function to sort the "start_date" field in ASC and also sort in DESC ordering using only JavaScript?

我使用了三张相联

var sort_by = function(field, reverse, primer){

   reverse = (reverse) ? -1 : 1;

   return function(a,b){

       a = a[field];
       b = b[field];

       if (typeof(primer) != 'undefined'){
           a = primer(a);
           b = primer(b);
       }

       if (a<b) return reverse * -1;
       if (a>b) return reverse * 1;
       return 0;

   }
}

并以以下方式申请

// Sort by start_time
homes.sort(sort_by('start_time', false, function(a){return a.getTime()}));

但不起作用..:((,给出此错误

but not working..:((, give this error

a.getTime is not a function

请告诉我我在哪里做错..

please tell me where i m doing mistake..

预先感谢

注意:很抱歉复制相同的内容 问题...

Note: sorry for copying same question...

推荐答案

正如我在评论中所说,字符串没有getTime()方法.只有Date对象具有.因此,您必须将日期字符串转换为Date对象.将您的功能更改为:

As I said in the comment, a string does not have a getTime() method. Only Date objects have. Therefore you have to convert the date string into a Date object. Change your function to:

function(a){return (new Date(a)).getTime()}

现在,Date有多种实现,我认为只有较新的实现才支持这种日期字符串的解析(虽然不确定).也许您必须先解析字符串,然后将单个值传递给Date:

Now, there are various implementations of Date and I think only the newer ones support parsing of this kind of date string (not sure though). Maybe you have to parse the string first and pass the single values to Date:

function(a){
    var parts = a.match(/(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/);
    var date = new Date(parts[1], parts[2], parts[3], parts[4], parts[5], parts[6]);
    return date.getTime()}
}

参考: Date

这篇关于如何按时间对JSON数组排序?(不像以前建议的那样工作)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆