2012-03-20 133 views
1

我嘗試通過使用嵌套的對象屬性以'分數'屬性的升序來按數字順序對數組中的對象進行排序。如何通過嵌套的對象屬性對對象的分析的JS數據進行排序

The Array;

[ {name:'dan', score:220}, 
    {name:'lucy', score:876}, 
    {name:'mike', score:211} ] 

我發現了以下線程,但尚未設法使其工作。

How to sort a JavaScript array of objects by nested object property?

控制檯輸出不確定的。

function order_top_scores(prop, arr) { 
    arr.sort(function (a, b) { 
     if (a[prop] < b[prop]) { 
     return -1; 
     } else if (a[prop] > b[prop]) { 
     return 1; 
     } else { 
     return 0; 
     } 
    }); 
}; 

function get_results(){ 
    $.get(wp_theme_dir+'/dottodot.php', 
     function(data){ 
     var returnedData = $.parseJSON(data); 
     var ordered_scores = order_top_scores(returnedData)  
     console.log(returnedData); 

    }); 
} 

我的數組略有不同,會不會是第二個屬性這就是打亂排序? 或者也許我從ajax請求處理數據的方式。

在此先感謝, 凸輪

+0

檢查你函數簽名。它預計2個參數 – 2012-03-20 11:42:12

+0

遺憾,這是一個監督當我簡化的示例中,仍然輸出未定義壽。 – Cam 2012-03-20 12:17:05

回答

2

你好嗎?

我剛剛測試過這個,還有一些你可能想要修改的東西。

首先,你用誰從問的人,而不是實際的解決方案的「排序」的解決方案,所以你首先需要重寫order_top_scores,像這樣:

 var order_top_scores = function (prop, arr,reverse) { 
      if(!reverse) reverse = 0; 
      prop = prop.split('.'); 
      var len = prop.length; 

      arr.sort(function (a, b) { 
       var i = 0; 
       while(i < len) { a = a[prop[i]]; b = b[prop[i]]; i++; } 
       if (a < b) { 
        return -1; 
       } else if (a > b) { 
        return 1; 
       } else { 
        return 0; 
       } 
      }); 

      if(reverse){arr.reverse()}; 
      return arr; 
     }; 

分析此功能,我已經添加了第三個「反向」參數,該參數既可以是真或假(因爲原始解決方案從最低到最高排序,在這種情況下,您需要相反)

現在您已具備此功能,有兩件事你要記住:

首先

在這一行:

var ordered_scores = order_top_scores(returnedData); 

您還沒有發送第一個強制性的參數,它實際上告訴你要排序的對象,其屬性的函數:在這種情況下,「分數」。

所以,你必須這樣調用該函數:

var ordered_scores = order_top_scores('score',returnedData); 

如果你希望它是由高排序,以低,像這樣:

var ordered_scores = order_top_scores('score',returnedData,true); 

而且,要記住你是輸出「returnedData」值,而不是ordered_scores值,所以如果這條線:

console.log(returnedData); 

正在輸出不確定,這意味着你的JSON數據是不正確的。可以肯定的那種工作,你也應該輸出的ordered_scores這樣的:

console.log(ordered_scores); 

讓我知道,如果有什麼不清楚。

乾杯!

+0

謝謝fsodano,這個工作完美。升序/降序布爾值是一個很好的接觸。 – Cam 2012-03-20 12:23:34

+0

很高興工作!玩的開心 :) – fsodano 2012-03-20 12:25:30

0

我不知道這是正確的代碼:

var returnedData = $.parseJSON(data); 
var ordered_scores = order_top_scores(returnedData) 

order_top_scores和方法調用下面的變化可以正常工作,如果returnedData是數組,你所提到的在你的問題:

function get_results(){ 
    $.get(wp_theme_dir+'/dottodot.php', 
     function(data){ 
     var returnedData = $.parseJSON(data); 
     var ordered_scores = order_top_scores("score", returnedData); 
     console.log(returnedData); 

    }); 
} 

function order_top_scores(prop, arr) { 
    arr.sort(function (a, b) { 
      if (a[prop] < b[prop]) { 
      return -1; 
      } else if (a[prop] > b[prop]) { 
      return 1; 
      } else { 
      return 0; 
      } 
     }); 
} 

你可以檢查輸出here in控制檯

相關問題