2015-12-24 155 views
-1

我有一個json feed,裏面有文章(每隔幾天就會有新文章),我需要獲得最新的三篇文章。問題是,json沒有按日期排序,我不知道如何按日期重新排列它最新到最舊。我使用js/jQuery。我的json文件如下所示:如何按日期對Json進行排序(最新到最舊)

[ 
{ 
    "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) 
. 
] 
+0

你使用JavaScript來管理你的JSON的內容? – benjguin

+1

哦,對不起忘了提及,我使用js/jQuery。 – Mrkun

回答

0

您可以使用Array.sort()函數。事情是這樣的:

(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; 
 
    })); 
 
})();

+0

完美地工作。我剛剛意識到,我過於複雜了,沒有任何工作。非常感謝 :) – Mrkun

相關問題