如何按日期对Json进行排序(最新到最旧) [英] How to sort Json by date (newest to oldest)

查看:52
本文介绍了如何按日期对Json进行排序(最新到最旧)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有文章的json提要(每隔几天就会有新的提要),我需要获取最新的三个.问题是,json不按日期排序,我也不知道如何按日期将其从新到旧排列.我使用js/jQuery.我的json文件看起来像这样:

i have a json feed with articles in it (and new coming every few days) and i need to get latest three out. The problem is, that json is not sorted by date and i don't know, how to rearrange it newest to oldest by date. I use js/jQuery. My json file looks like this:

[  
{  
  "author":"some text",
  "title":"some text",
  "description":"some text",
  "image_big":"image link",
  "image_small":"image link",
  "date":"2015-06-17",
  "content":"some text some text some text some text some text",
  "category":"category",
  "subcategory":[
     "some subcategory"
  ],
  "keywords":"keywords,keywords...",
  "id":"45654",
  "url":"article link"
},
.
. (more articles)
.
]

推荐答案

您可以使用 Array.sort()函数.像这样:

You can use Array.sort() function. Something like this:

(function() {
  var data = [{
    "author": "some text",
    "title": "some text",
    "description": "some text",
    "image_big": "image link",
    "image_small": "image link",
    "date": "2015-06-17",
    "content": "some text some text some text some text some text",
    "category": "category",
    "subcategory": [
      "some subcategory"
    ],
    "keywords": "keywords,keywords...",
    "id": "45654",
    "url": "article link"
  }, {
    "author": "some text 2",
    "title": "some text 2",
    "description": "some text 2",
    "image_big": "image link 2",
    "image_small": "image link 2",
    "date": "2015-06-20",
    "content": "some text some text some text some text some text",
    "category": "category",
    "subcategory": [
      "some subcategory"
    ],
    "keywords": "keywords,keywords...",
    "id": "45654",
    "url": "article link"
  }];


  console.log(data.sort(function(a, b) {
    return b.date > a.date;
  }));
})();

这篇关于如何按日期对Json进行排序(最新到最旧)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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