Ajax响应我得到的结果如下:
"students":[{
"student_id":"27",
"job_id":"12",
"128":"8",
"63":"9",
"3":"10",
"weightage":"5.6000"}
,{"student_id":"22",
"job_id":"12",
"128":"5",
"63":"6",
"3":"8",
"weightage":"9.1000"
}]}
由此我想显示相同的顺序,因为权重(总分)很高,它应该在最后一个较小的一个。
如何按描述过滤? 这是我的代码:
console.log(response['students']);
$.each(response['students'], function(k, student) {
$("#stu"+student.student_id).removeClass('btn-danger reject-student');
$("#stu"+student.student_id).addClass('btn-success select-student');
$("#stu"+student.student_id).text('Student Selected');
});
/*Sorting select-student students at one place starts here*/
var rows = document.querySelectorAll('table tbody tr.sorted');
for (i = 0; i < rows.length; i++) {
if (rows[i].querySelector('span.reject-student')) {
rows[i].closest('tbody').appendChild(rows[i]);
}
}
/*Sorting select-student students at one place ends here*/
答案 0 :(得分:2)
这很简单。将响应JSON字符串解析为对象。请尝试以下方法:
// Array of student objects
var students = JSON.parse("Your response json string");
//Sort this array by weightage property in descending order
students.sort(function(a,b){
return b.weightage - a.weightage; // descending order
});
见下面的小提琴:
var response = '[{"student_id": "27","job_id": "12","128": "8","63": "9","3": "10","weightage": "5.6000"}, {"student_id": "22","job_id": "12","128": "5","63": "6","3": "8","weightage": "9.1000"}]';
var students = JSON.parse(response);
students.sort(function(a,b){
return b.weightage - a.weightage; // descending order
});
alert(students[0].weightage);
alert(students[1].weightage);
希望这会有所帮助:)
答案 1 :(得分:0)
var rows = document.querySelectorAll('table tbody tr.sorted');
$.each(response['students'], function(k, student) {
$("#stu"+student.student_id).removeClass('btn-danger reject-student');
$("#stu"+student.student_id).addClass('btn-success select-student');
$("#stu"+student.student_id).text('Student Selected');
/* Sorting by student overall score starts here */
for (i = 0; i < rows.length; i++) {
if (rows[i].querySelector('span#stu'+student.student_id)) {
rows[i].closest('tbody').appendChild(rows[i]);
}
}
/* Sorting by student overall score ends here */
});