使用 Knockout .sort() 对 JSON 数据进行排序

Sorting JSON data with Knockout .sort()

我可以使用 Knockout 的 .sort() 对数据进行排序。但是,当我尝试根据用户的点击进行动态排序时,排序就会变得混乱。这是我的代码:

var patientReport = [{"first_name":"Lyle","last_name":"Erickson","patient_id":1000},{"first_name":"Janna","last_name":"Barr","patient_id":1001},{"first_name":"Shelly","last_name":"Delacruz","patient_id":1002},{"first_name":"Nissim","last_name":"Wong","patient_id":1003},{"first_name":"Yvonne","last_name":"Rocha","patient_id":1004},{"first_name":"Leo","last_name":"Holland","patient_id":1005},{"first_name":"Melinda","last_name":"Curtis","patient_id":1006},{"first_name":"Orlando","last_name":"Peters","patient_id":1007},{"first_name":"Miriam","last_name":"Bates","patient_id":1008},{"first_name":"Otto","last_name":"Hurley","patient_id":1009},{"first_name":"Doris","last_name":"Byrd","patient_id":1010}];

var myObservableArray = ko.observableArray(patientReport);

$('.sort_header').on('click', function() {
 var data = $(this).data('header');
 sortRows(data);
});

function sortRows(row) {
 myObservableArray.sort(
  function(left, right) {
   return left.row == right.row ? 0 : (left.row < right.row ? -1 : 1);
  }
 ); 
}

知道出了什么问题吗?

您需要使用 left[row] 而不是 left.rowright 也是如此)。您拥有它的方式是尝试按 属性 实际上称为 "row" 进行排序。使用方括号语法,您可以将 属性 与 变量 row.

指定的名称一起使用
function sortRows(row) {
  myObservableArray.sort(
    function(left, right) {
      return left[row] == right[row] ? 0 : (left[row] < right[row] ? -1 : 1);
    }
  );    
}