gpt4 book ai didi

javascript - 如何按 id 值从最新到最旧对 JSON 进行排序

转载 作者:行者123 更新时间:2023-11-27 22:32:35 26 4
gpt4 key购买 nike

如何按 ID 值从最新到最旧对 JSON 进行排序?

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

结果:

id:1
name:Mary
category:eng

id:2
name:Peter
category:super

id:3
name:Ben
category:math

我想要的结果是:

id:3
name:Ben
category:math

id:2
name:Peter
category:super
id:1

name:Mary
category:eng

id:3 --> id-->2 id:--1

最佳答案

在操作 dom 之前,按照 id 的降序对结果进行排序

var sortedResult = result.sort(function(a, b) {
return b.id - a.id
})
$.each(sortedResult, function(i, field) {
// Rest of the code
});

关于javascript - 如何按 id 值从最新到最旧对 JSON 进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39422234/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com