2013-01-13 49 views
2

可能重複:
Sorting JavaScript Object by property valueJavascript - 計數重複的JSON值和排序計數與關聯密鑰?

我想爲我的JSON內的一些數值結果的最前面。更容易的例子來說明:

var jsonData = { 
    bom: [ 
     { 
      "Component":"Some Thing", 
      "Version":"Version ABC", 
      "License":"License ABC", 
     }, 
     { 
      "Component":"Another Thing", 
      "Version":"Version XYZ", 
      "License":"License ABC", 
     }, 
     etc .... 
     ] 
} 

所以我的目標是確定「許可證ABC」或者其他具有出現X號,然後我希望能夠排序的關鍵:val對的形式插入到到DOM爲「頂X最流行的許可證是:

  • 許可ABC - 100
  • 許可XYZ - 70
  • 許可證123 - 25

現在我有這樣的:

var countResults = function() { 
    var fileLicenses = []; 

    for (var i = 0, arrLen = jsonData.files.length; i < arrLen; ++i) { 
     fileLicenses.push(jsonData.files[i]["License"]); 
    } 

    keyCount = {}; 
    for(i = 0; i < fileLicenses.length; ++i) { 
     if(!keyCount[fileLicenses[i]]) { 
      keyCount[fileLicenses[i]] = 0; 
     } 

     ++keyCount[fileLicenses[i]]; 
    } 

    console.log(keyCount); 
}(); 

當中去是我的大部分我想要的東西,與主要的對象:值

{ 
    thisKey : 78, 
    thatKey :125, 
    another key : 200, 
    another key : 272, 
    another key : 45, 
    etc ... 
} 

但我不知道怎麼跟那個做什麼。我只需要對數字右邊的列進行排序,並讓相關的鍵保持一致。思考?謝謝!

回答

4

您無法按對象的值排序對象。你可以做的是將其轉換爲一個對象數組,然後對其進行排序。喜歡的東西:

var rank = function(items, prop) { 

    //declare a key->count table 
    var results = {} 

    //loop through all the items we were given to rank 
    for(var i=0;len=items.length;i<len;i++) { 

    //get the requested property value (example: License) 
    var value = items[i][prop]; 

    //increment counter for this value (starting at 1) 
    var count = (results[value] || 0) + 1; 
    results[value] = count; 
    } 

    var ranked = [] 

    //loop through all the keys in the results object 
    for(var key in results) { 

    //here we check that the results object *actually* has 
    //the key. because of prototypal inheritance in javascript there's 
    //a chance that someone has modified the Object class prototype 
    //with some extra properties. We don't want to include them in the 
    //ranking, so we check the object has it's *own* property. 
    if(results.hasOwnProperty(key)) { 

     //add an object that looks like {value:"License ABC", count: 2} 
     //to the output array 
     ranked.push({value:key, count:results[key]}); 
    } 
    } 

    //sort by count descending 
    return ranked.sort(function(a, b) { return b.count - a.count; }); 
} 

用法:

var sorted = rank(jsonData.bom, "License"); 
var first = sorted[0].value; 

/代碼沒有測試

+0

感謝fencliff!插入它,它很好。仍然需要一些時間來理解邏輯,但只是我需要的。謝謝! – Matt

+0

@Matt我在代碼中添加了一些註釋來解釋邏輯。如果解決方案有效,請不要忘記將答案標記爲已接受! – jevakallio

+0

哇。真的很欣賞Fencliff的評論。該解決方案從一開始就工作得很好,但最好理解你所插入的東西!這有助於。再次感謝! – Matt