7

可能重复:
按 JavaScript 中的字段值对数组中的对象进行排序

 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 li .. 怎么可能用距离最短的列表排序等等。

4

1 回答 1

5

那不是 JSON。它已经是一个 JavaScript 对象数组,所以你只需使用.sort().

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

0请注意,如果数字转换.Distance失败,我将替换。

请阅读 MDN 文档.sort()以了解有关对 JavaScript 数组进行排序的更多信息。


$.each()要创建元素,您可以使用迭代器循环排序数组。

var list = $("#mylist");

$.each(myData, function(i, obj) {
    $("<li>", {
         text: obj.Naam + ": Distance - " + obj.Distance
    }).appendTo(list);
});
于 2012-10-16T13:15:14.760 回答