根据日期和时间对JSON数据进行排序

时间:2016-12-08 08:14:54

标签: javascript jquery json

是否可以使用jQuery / Javascript根据时间(2016-12-07T13:00:00)重新排列以下JSON格式。

[
   {
      "id":1,
      "start":"2016-12-07T13:00:00",
      "subject":"test1",
   },
   {
      "id":2,
      "start":"2016-12-07T09:00:00",
      "subject":"test2",
   },
   {
      "id":3,
      "start":"2016-12-07T10:00:00",
      "subject":"test3",
   },
   {
      "id":4,
      "start":"2016-12-07T07:00:00",
      "subject":"test4",
   },
   {
      "id":5,
      "start":"2016-12-07T14:00:00",
      "subject":"test5",
   }
]

4 个答案:

答案 0 :(得分:5)

您可以在属性start的排序回调中使用String#localeCompare,因为ISO 8601日期可以排序为字符串。

var array = [
    { id: 1, start: "2016-12-07T13:00:00", subject: "test1" },
    { id: 2, start: "2016-12-07T09:00:00", subject: "test2" },
    { id: 3, start: "2016-12-07T10:00:00", subject: "test3" },
    { id: 4, start: "2016-12-07T07:00:00", subject: "test4" },
    { id: 5, start: "2016-12-07T14:00:00", subject: "test5" }
];

array.sort(function (a, b) {
    return a.start.localeCompare(b.start);
});

console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:0)

如果您可以使用外部库,例如Lodash

https://lodash.com/

将json字符串分配给变量并尝试

var sort = _.sortBy(variable_name, "start")
希望这会帮助你。

答案 2 :(得分:0)

尝试这可能有帮助,

var aryData =[
   {
      "id":1,
      "start":"2016-12-07T13:00:00",
      "subject":"test1",
   },
   {
      "id":2,
      "start":"2016-12-07T09:00:00",
      "subject":"test2",
   },
   {
      "id":3,
      "start":"2016-12-07T10:00:00",
      "subject":"test3",
   },
   {
      "id":4,
      "start":"2016-12-07T07:00:00",
      "subject":"test4",
   },
   {
      "id":5,
      "start":"2016-12-07T14:00:00",
      "subject":"test5",
   }
];
    function comp(a, b) {
        return new Date(a.start).getTime() - new Date(b.start).getTime();
    }
    aryData.sort(comp);

console.log(aryData);

答案 3 :(得分:0)



//put to variable
var db = [
   {
      "id":1,
      "start":"2016-12-07T13:00:00",
      "subject":"test1",
   },
   {
      "id":2,
      "start":"2016-12-07T09:00:00",
      "subject":"test2",
   },
   {
      "id":3,
      "start":"2016-12-07T10:00:00",
      "subject":"test3",
   },
   {
      "id":4,
      "start":"2016-12-07T07:00:00",
      "subject":"test4",
   },
   {
      "id":5,
      "start":"2016-12-07T14:00:00",
      "subject":"test5",
   }
];

//use .sort()
db.sort(
  function(a,b){ 
    
    //use new Date parse string to date type
    //convert date to number use Date.parse()
    //format function(a,b) { return a-b; }
    
    return Date.parse(new Date(a.start)) - Date.parse(new Date(b.start)); 
  }
);
console.log(db)