user2718017 user2718017 - 1 month ago 10
jQuery Question

Sort JSON table by Value

I want to sort my JSON table by the Value data.FuelState.

Unfortionally it turns back, that data.sort is no function. Whats wrong? Is the basis sort function correct?

<!DOCTYPE html>
<html>
<head>
//..//
</head>

<body>
<script src="js/bootstrap.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
function callJSON() {
setTimeout(function () {
$.getJSON('./url.php', function(data) {
$("#usertable").empty();
data.sort(function(a,b) {
return parseFloat(b.fuelState) - parseFloat(a.fuelState);
});

var cars = data.rec.vehicles.vehicles;
$.each(cars, function(key, data){
//..//
$('#usertable').append(
function() {
return "<tr class="+farbe+">" +
"<td><span class='glyphicon glyphicon-user'></span> "+data.carName+"</td>" +
//..//
"<tr>";
}
);
});
}).always(callJSON);
}, 2000);
}
$(callJSON);
});
</script>
</body>
</html>


JSON:

{"err":[],"msg":[],"state":null,"rec":{"vehicles":{"search_criteria":[{"auto":"N","group":"BMW","model":"BMW 1er "},{"auto":"N","group":"MINI","model":"MINI Cooper"},{"auto":"Y","group":"BMW","model":"BMW 1er "},{"auto":"Y","group":"MINI","model":"MINI Cooper"},{"auto":"N","group":"MINI","model":"MINI Clubman"},{"auto":"Y","group":"","model":" ActiveE "},{"auto":"N","group":"MINI","model":"MINI Cabrio"},{"auto":"Y","group":"BMW","model":"BMW X1 "},{"auto":"N","group":"BMW","model":"BMW X1 "},{"auto":"Y","group":"BMW","model":"BMW ActiveE "},{"auto":"N","group":"BMW","model":"BMW 1er Cabrio"},{"auto":"Y","group":"MINI","model":"MINI Clubman"},{"auto":"N","group":"MINI","model":"MINI Coup\u00e9"},{"auto":"Y","group":"MINI","model":"MINI Coup\u00e9"},{"auto":"N","group":"BMW","model":"BMW ActiveE "}],"statistics":[],"vehicles":[{"position":{"latitude":"48.055301944444","longitude":"11.607825833333","address":"Inselkammerstra\u00dfe 4, 82008 Unterhaching"},"vin":"WBAUD71000P448627","int":"12166478","auto":"N","carName":"Fausto","cit":"7586","color":"ALPINWEISS","fuelState":"21","fuelType":"DDE","group":"BMW","innerCleanliness":"CLEAN","licensePlate":"M -N 2651","pgid":"0","model":"BMW 1er ","cd":"0","milliageMetricsName":"0","address":"Inselkammerstra\u00dfe 4, 82008 Unterhaching","personalName":"BMW 1er : Fausto","price":{"drive":"31","park":"10"}},{"position":{"latitude":"52.541172777778","longitude":"13.325585833333","address":"Saatwinkler Damm 15-17, 13627 Berlin"}

Answer

Data is your full JSON sample, which is an object that hold other data and the vihicles are only asub creteria of it.

The actual cars can be found under

data.rect.vehicles.vehicles

(the one which you assigned cars to)

So applying the sort function to cars works:

        var cars = data.rec.vehicles.vehicles;

        cars.sort(function(a,b) {
            return parseFloat(b.fuelState) - parseFloat(a.fuelState);
        });
Comments