2012-10-16 53 views
1

可能重複:
Sorting objects in an array by a field value in JavaScript排序一個json列表?

var myData = [ 
        {"Identifier":1,"Naam":"Van Der Valk","Adres":"Europaweg 218","Postcode":"1238AC","Plaats":"Zoetermeer","Longitude":"4.48822","Latitude":"52.06258", "Status":"Laadpunten Beschikbaar", "lunch":"true", "diner":"true", "meet":"true", "wifi":"true", "Distance": "10.1"}, 
        {"Identifier":2,"Naam":"Meram place","Adres":"NOT Given 1","Postcode":"0000LL","Plaats":"Rotterdam","Longitude":"4.48178","Latitude":"51.92422", "lunch":"false", "Distance": "181"}, 
        {"Identifier":3,"Naam":"Station Zwolle","Adres":"NOT Given 6","Postcode":"0000LL","Plaats":"Zwolle","Longitude":"6.08302","Latitude":"52.51677", "lunch":"false", "Distance": "5.1"}, 
        {"Identifier":4,"Naam":"Pompstation Shell","Adres":"NOT Given 1","Postcode":"0000LL","Plaats":"Den Haag","Longitude":"4.30070","Latitude":"52.07050", "lunch":"false"}, 
        {"Identifier":5,"Naam":"Amsterdam Arena","Adres":"NOT Given 218","Postcode":"0000LL","Plaats":"Amsterdam","Longitude":"4.89517","Latitude":"52.37022", "lunch":"true", "diner":"true", "wifi":"true", "meet":"true", "Distance": "34.2"} 
        ]; 

我有一個問題,因爲我有上面的JSON ..我想追加這清單即UL李..怎麼可能得到與最低距離等列表排序列表

+0

命令由什麼?列表格式化如何? – skovalyov

回答

3

這不是JSON。它已經是JavaScript對象數組,因此您只需使用.sort()

myData.sort(function(a, b) { 
    return (+a.Distance || 0) - (+b.Distance || 0); 
}); 

請注意,我代0如果.Distance數字轉換失敗。

請閱讀.sort()的MDN文檔以瞭解有關排序JavaScript數組的更多信息。


要創建的元素,可以循環使用$.each()迭代數組排序。

var list = $("#mylist"); 

$.each(myData, function(i, obj) { 
    $("<li>", { 
     text: obj.Naam + ": Distance - " + obj.Distance 
    }).appendTo(list); 
});