[英]Sort a JSON alphabetically using JQuery and print to a table
因此,我嘗試使用json並將其按字母順序排序,然后創建表並將信息動態地放入各自的表中。 我似乎無法讓他們按字母順序排序。 以下是我的JQuery:
<script>
function populateDept(){
$.ajax({
type: 'GET',
url: 'https://dl.dropboxusercontent.com/s/sslmd5y53uusgfx/depts.json',
data: { get_param: 'value' },
dataType: 'json',
success: function (data) {
$.each(data, function(index, element) {
data.sort(function(a,b){
return a[1] > b[1] ? 1: -1;
});
var classAcr ="." + element.acronym;
$('#content').prepend($('<table class="aui aui-sortable">').addClass(element.acronym + ""));
$(classAcr).append($('<thead>').css("text-align", "left").append($('<tr>').append($('<th>', {
text: element.name
})).append($('<th>', {
text: element.acronym
}))));
for (var i = 0; i < element.departments.length; i++) {
$(classAcr).append($('<tr>').append($('<td>', {
text: element.departments[i].name
})).append($('<td>', {
text: element.departments[i].acronym
})));
}
});
$("th").css("width","50%");
$("th").css("width","50%");
$("table").append("<br>");
$("th").css("font-weight", "bold");
$("th").css("font-size", "35px");
}
});
}
populateDept();
</script>
我正在使用的json看起來像這樣,但是列出了更多部門。 我正在嘗試按“名稱”:“學術事務”等對它們進行排序。
[{
"name": "Academic Affairs",
"acronym": "ACAD",
"departments": [{
"name": "International Education and Global Programs",
"acronym": "IEGP"
},
{
"name": "Graduate Studies",
"acronym": "GRAD"
},
{
"name": "RIT Honors Program",
"acronym": "Honors"
},
{
"name": "Institute Advising",
"acronym": "IADV"
},
{
"name": "Innovative Learning Institute",
"acronym": "ILI"
},
{
"name": "K12 Programs",
"acronym": "K12"
},
{
"name": "Office of the Registrar",
"acronym": "RGR"
},
{
"name": "RIT Online",
"acronym": "RITO"
},
{
"name": "Study Abroad Program",
"acronym": "SAP"
},
{
"name": "Student Learning Outcomes Assessment",
"acronym": "SLOA"
},
{
"name": "School of Individualized Study",
"acronym": "SOIS"
},
{
"name": "Teaching and Learning Studio",
"acronym": "TLS"
},
{
"name": "University Studies Program",
"acronym": "USP"
},
{
"name": "University Writing Program",
"acronym": "UWP"
}]
如果要按名稱對對象數組進行排序,請嘗試以下一種方法:
var jsonArray; //your json array
jsonArray.sort(function(a,b){
returb a.name > b.name;
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.