How to sort JSON by ID's values newest to oldest?
HTML:
<script>
$(document).ready(function() {
var url = "json.php";
$.getJSON(url, function(result) {
console.log(result);
$.each(result, function(i, field) {
var id = field.id;
var name = field.name;
var category = field.category;
$("#show_data").append("<li class='item'>"+"<div>"+ id +"</div>"+ "<p>"+ name +"</p>" +"<p>" + category +"</p></li>");
});
});
});</script><body><ul><div id="show_data"></div><ul>
Json.php:
[{
"id": "1",
"name": "Mary",
"category": "eng"
}, {
"id": "2",
"name": "Peter",
"category": "super"
}, {
"id": "3",
"name": "Ben",
"category": "math"
}]
Results:
id:1
name:Mary
category:eng
id:2
name:Peter
category:super
id:3
name:Ben
category:math
I want the results to be:
id:3
name:Ben
category:math
id:2
name:Peter
category:super
id:1
name:Mary
category:eng
id:3 --> id-->2 id:--1
Sort the result
in descending order of id
before manipulating the dom
var sortedResult = result.sort(function(a, b) {
return b.id - a.id
})
$.each(sortedResult, function(i, field) {
// Rest of the code
});
If you just want it to show up in reverse order, you can just use $("show_data").prepend(data)
. This will insert the last data to be prepended on the top of the div, and the first on the bottom.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.