Tuesday, August 6, 2019

javascript - sorting a json list?











 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"}
];


I have a question, given I have the above json.. and i want to append this to a list i.e ul li.. how is it possible to get the list ordered with the one with the lowest distance etc.


Answer



That's not JSON. It's already a JavaScript Array of Objects, so you'd just use .sort().



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

});


Note that I'm substituting 0 if the numeric conversion of .Distance failed.



Please read the MDN docs for .sort() to learn more about sorting JavaScript Arrays.






To create elements, you can loop the sorted array using the $.each() iterator.




var list = $("#mylist");

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

  • No comments:

    Post a Comment

    hard drive - Leaving bad sectors in unformatted partition?

    Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...